@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,1367 +1,1367 @@
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/common/fileService.ts
22
- // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/textfile/browser/textFileService.ts
23
- // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/textfile/electron-browser/nativeTextFileService.ts
24
- // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/workingCopy/common/workingCopyFileService.ts
25
- // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/workingCopy/common/workingCopyFileOperationParticipant.ts
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.FileService = exports.TextFileOperationError = exports.FileServiceContribution = void 0;
28
- const tslib_1 = require("tslib");
29
- /* eslint-disable max-len */
30
- /* eslint-disable @typescript-eslint/no-shadow */
31
- /* eslint-disable no-null/no-null */
32
- /* eslint-disable @typescript-eslint/tslint/config */
33
- /* eslint-disable @typescript-eslint/no-explicit-any */
34
- const inversify_1 = require("@theia/core/shared/inversify");
35
- const promise_util_1 = require("@theia/core/lib/common/promise-util");
36
- const cancellation_1 = require("@theia/core/lib/common/cancellation");
37
- const disposable_1 = require("@theia/core/lib/common/disposable");
38
- const event_1 = require("@theia/core/lib/common/event");
39
- const contribution_provider_1 = require("@theia/core/lib/common/contribution-provider");
40
- const ternary_search_tree_1 = require("@theia/core/lib/common/ternary-search-tree");
41
- const files_1 = require("../common/files");
42
- const buffer_1 = require("@theia/core/lib/common/buffer");
43
- const stream_1 = require("@theia/core/lib/common/stream");
44
- const label_provider_1 = require("@theia/core/lib/browser/label-provider");
45
- const filesystem_preferences_1 = require("./filesystem-preferences");
46
- const progress_service_1 = require("@theia/core/lib/common/progress-service");
47
- const delegating_file_system_provider_1 = require("../common/delegating-file-system-provider");
48
- const encoding_registry_1 = require("@theia/core/lib/browser/encoding-registry");
49
- const encodings_1 = require("@theia/core/lib/common/encodings");
50
- const encoding_service_1 = require("@theia/core/lib/common/encoding-service");
51
- const io_1 = require("../common/io");
52
- const filesystem_watcher_error_handler_1 = require("./filesystem-watcher-error-handler");
53
- const filesystem_utils_1 = require("../common/filesystem-utils");
54
- const core_1 = require("@theia/core");
55
- exports.FileServiceContribution = Symbol('FileServiceContribution');
56
- class TextFileOperationError extends files_1.FileOperationError {
57
- constructor(message, textFileOperationResult, options) {
58
- super(message, 11 /* FILE_OTHER_ERROR */);
59
- this.textFileOperationResult = textFileOperationResult;
60
- this.options = options;
61
- Object.setPrototypeOf(this, TextFileOperationError.prototype);
62
- }
63
- }
64
- exports.TextFileOperationError = TextFileOperationError;
65
- /**
66
- * The {@link FileService} is the common facade responsible for all interactions with file systems.
67
- * It manages all registered {@link FileSystemProvider}s and
68
- * forwards calls to the responsible {@link FileSystemProvider}, determined by the scheme.
69
- * For additional documentation regarding the provided functions see also {@link FileSystemProvider}.
70
- */
71
- let FileService = class FileService {
72
- constructor() {
73
- this.BUFFER_SIZE = 64 * 1024;
74
- // #region Events
75
- this.correlationIds = 0;
76
- this.onWillRunUserOperationEmitter = new event_1.AsyncEmitter();
77
- /**
78
- * An event that is emitted when file operation is being performed.
79
- * This event is triggered by user gestures.
80
- */
81
- this.onWillRunUserOperation = this.onWillRunUserOperationEmitter.event;
82
- this.onDidFailUserOperationEmitter = new event_1.AsyncEmitter();
83
- /**
84
- * An event that is emitted when file operation is failed.
85
- * This event is triggered by user gestures.
86
- */
87
- this.onDidFailUserOperation = this.onDidFailUserOperationEmitter.event;
88
- this.onDidRunUserOperationEmitter = new event_1.AsyncEmitter();
89
- /**
90
- * An event that is emitted when file operation is finished.
91
- * This event is triggered by user gestures.
92
- */
93
- this.onDidRunUserOperation = this.onDidRunUserOperationEmitter.event;
94
- // #endregion
95
- // #region File System Provider
96
- this.onDidChangeFileSystemProviderRegistrationsEmitter = new event_1.Emitter();
97
- this.onDidChangeFileSystemProviderRegistrations = this.onDidChangeFileSystemProviderRegistrationsEmitter.event;
98
- this.onWillActivateFileSystemProviderEmitter = new event_1.Emitter();
99
- /**
100
- * See `FileServiceContribution.registerProviders`.
101
- */
102
- this.onWillActivateFileSystemProvider = this.onWillActivateFileSystemProviderEmitter.event;
103
- this.onDidChangeFileSystemProviderCapabilitiesEmitter = new event_1.Emitter();
104
- this.onDidChangeFileSystemProviderCapabilities = this.onDidChangeFileSystemProviderCapabilitiesEmitter.event;
105
- this.onDidChangeFileSystemProviderReadOnlyMessageEmitter = new event_1.Emitter();
106
- this.onDidChangeFileSystemProviderReadOnlyMessage = this.onDidChangeFileSystemProviderReadOnlyMessageEmitter.event;
107
- this.providers = new Map();
108
- this.activations = new Map();
109
- // #endregion
110
- this.onDidRunOperationEmitter = new event_1.Emitter();
111
- /**
112
- * An event that is emitted when operation is finished.
113
- * This event is triggered by user gestures and programmatically.
114
- */
115
- this.onDidRunOperation = this.onDidRunOperationEmitter.event;
116
- // #endregion
117
- // #region File Watching
118
- this.onDidFilesChangeEmitter = new event_1.Emitter();
119
- this.activeWatchers = new Map();
120
- // #endregion
121
- // #region Helpers
122
- this.writeQueues = new Map();
123
- // #endregion
124
- // #region File operation participants
125
- this.participants = [];
126
- }
127
- init() {
128
- for (const contribution of this.contributions.getContributions()) {
129
- contribution.registerFileSystemProviders(this);
130
- }
131
- }
132
- /**
133
- * Registers a new {@link FileSystemProvider} for the given scheme.
134
- * @param scheme The (uri) scheme for which the provider should be registered.
135
- * @param provider The file system provider that should be registered.
136
- *
137
- * @returns A `Disposable` that can be invoked to unregister the given provider.
138
- */
139
- registerProvider(scheme, provider) {
140
- if (this.providers.has(scheme)) {
141
- throw new Error(`A filesystem provider for the scheme '${scheme}' is already registered.`);
142
- }
143
- this.providers.set(scheme, provider);
144
- this.onDidChangeFileSystemProviderRegistrationsEmitter.fire({ added: true, scheme, provider });
145
- const providerDisposables = new disposable_1.DisposableCollection();
146
- providerDisposables.push(provider.onDidChangeFile(changes => this.onDidFilesChangeEmitter.fire(new files_1.FileChangesEvent(changes))));
147
- providerDisposables.push(provider.onFileWatchError(() => this.handleFileWatchError()));
148
- providerDisposables.push(provider.onDidChangeCapabilities(() => this.onDidChangeFileSystemProviderCapabilitiesEmitter.fire({ provider, scheme })));
149
- if (files_1.ReadOnlyMessageFileSystemProvider.is(provider)) {
150
- providerDisposables.push(provider.onDidChangeReadOnlyMessage(message => this.onDidChangeFileSystemProviderReadOnlyMessageEmitter.fire({ provider, scheme, message })));
151
- }
152
- return disposable_1.Disposable.create(() => {
153
- this.onDidChangeFileSystemProviderRegistrationsEmitter.fire({ added: false, scheme, provider });
154
- this.providers.delete(scheme);
155
- providerDisposables.dispose();
156
- });
157
- }
158
- /**
159
- * Try to activate the registered provider for the given scheme
160
- * @param scheme The uri scheme for which the responsible provider should be activated.
161
- *
162
- * @returns A promise of the activated file system provider. Only resolves if a provider is available for this scheme, gets rejected otherwise.
163
- */
164
- async activateProvider(scheme) {
165
- let provider = this.providers.get(scheme);
166
- if (provider) {
167
- return provider;
168
- }
169
- let activation = this.activations.get(scheme);
170
- if (!activation) {
171
- const deferredActivation = new promise_util_1.Deferred();
172
- this.activations.set(scheme, activation = deferredActivation.promise);
173
- event_1.WaitUntilEvent.fire(this.onWillActivateFileSystemProviderEmitter, { scheme }).then(() => {
174
- provider = this.providers.get(scheme);
175
- if (!provider) {
176
- const error = new Error();
177
- error.name = 'ENOPRO';
178
- error.message = `No file system provider found for scheme ${scheme}`;
179
- throw error;
180
- }
181
- else {
182
- deferredActivation.resolve(provider);
183
- }
184
- }).catch(e => deferredActivation.reject(e));
185
- }
186
- return activation;
187
- }
188
- /**
189
- * Tests if the service (i.e. any of its registered {@link FileSystemProvider}s) can handle the given resource.
190
- * @param resource `URI` of the resource to test.
191
- *
192
- * @returns `true` if the resource can be handled, `false` otherwise.
193
- */
194
- canHandleResource(resource) {
195
- return this.providers.has(resource.scheme);
196
- }
197
- getReadOnlyMessage(resource) {
198
- const provider = this.providers.get(resource.scheme);
199
- if (files_1.ReadOnlyMessageFileSystemProvider.is(provider)) {
200
- return provider.readOnlyMessage;
201
- }
202
- return undefined;
203
- }
204
- /**
205
- * Tests if the service (i.e the {@link FileSystemProvider} registered for the given uri scheme) provides the given capability.
206
- * @param resource `URI` of the resource to test.
207
- * @param capability The required capability.
208
- *
209
- * @returns `true` if the resource can be handled and the required capability can be provided.
210
- */
211
- hasCapability(resource, capability) {
212
- const provider = this.providers.get(resource.scheme);
213
- return !!(provider && (provider.capabilities & capability));
214
- }
215
- /**
216
- * List the schemes and capabilities for registered file system providers
217
- */
218
- listCapabilities() {
219
- return Array.from(this.providers.entries()).map(([scheme, provider]) => ({
220
- scheme,
221
- capabilities: provider.capabilities
222
- }));
223
- }
224
- async withProvider(resource) {
225
- // Assert path is absolute
226
- if (!resource.path.isAbsolute) {
227
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to resolve filesystem provider with relative file path '{0}'", this.resourceForError(resource)), 8 /* FILE_INVALID_PATH */);
228
- }
229
- return this.activateProvider(resource.scheme);
230
- }
231
- async withReadProvider(resource) {
232
- const provider = await this.withProvider(resource);
233
- if ((0, files_1.hasOpenReadWriteCloseCapability)(provider) || (0, files_1.hasReadWriteCapability)(provider)) {
234
- return provider;
235
- }
236
- throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`);
237
- }
238
- async withWriteProvider(resource) {
239
- const provider = await this.withProvider(resource);
240
- if ((0, files_1.hasOpenReadWriteCloseCapability)(provider) || (0, files_1.hasReadWriteCapability)(provider)) {
241
- return provider;
242
- }
243
- throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`);
244
- }
245
- async resolve(resource, options) {
246
- try {
247
- return await this.doResolveFile(resource, options);
248
- }
249
- catch (error) {
250
- // Specially handle file not found case as file operation result
251
- if ((0, files_1.toFileSystemProviderErrorCode)(error) === files_1.FileSystemProviderErrorCode.FileNotFound) {
252
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to resolve nonexistent file '{0}'", this.resourceForError(resource)), 1 /* FILE_NOT_FOUND */);
253
- }
254
- // Bubble up any other error as is
255
- throw (0, files_1.ensureFileSystemProviderError)(error);
256
- }
257
- }
258
- async doResolveFile(resource, options) {
259
- const provider = await this.withProvider(resource);
260
- const resolveTo = options === null || options === void 0 ? void 0 : options.resolveTo;
261
- const resolveSingleChildDescendants = options === null || options === void 0 ? void 0 : options.resolveSingleChildDescendants;
262
- const resolveMetadata = options === null || options === void 0 ? void 0 : options.resolveMetadata;
263
- const stat = await provider.stat(resource);
264
- let trie;
265
- return this.toFileStat(provider, resource, stat, undefined, !!resolveMetadata, (stat, siblings) => {
266
- // lazy trie to check for recursive resolving
267
- if (!trie) {
268
- trie = ternary_search_tree_1.TernarySearchTree.forUris(!!(provider.capabilities & 1024 /* PathCaseSensitive */));
269
- trie.set(resource, true);
270
- if (Array.isArray(resolveTo) && resolveTo.length) {
271
- resolveTo.forEach(uri => trie.set(uri, true));
272
- }
273
- }
274
- // check for recursive resolving
275
- if (Boolean(trie.findSuperstr(stat.resource) || trie.get(stat.resource))) {
276
- return true;
277
- }
278
- // check for resolving single child folders
279
- if (stat.isDirectory && resolveSingleChildDescendants) {
280
- return siblings === 1;
281
- }
282
- return false;
283
- });
284
- }
285
- async toFileStat(provider, resource, stat, siblings, resolveMetadata, recurse) {
286
- const fileStat = files_1.FileStat.fromStat(resource, stat);
287
- // check to recurse for directories
288
- if (fileStat.isDirectory && recurse(fileStat, siblings)) {
289
- try {
290
- const entries = await provider.readdir(resource);
291
- const resolvedEntries = await Promise.all(entries.map(async ([name, type]) => {
292
- try {
293
- const childResource = resource.resolve(name);
294
- const childStat = resolveMetadata ? await provider.stat(childResource) : { type };
295
- return await this.toFileStat(provider, childResource, childStat, entries.length, resolveMetadata, recurse);
296
- }
297
- catch (error) {
298
- console.trace(error);
299
- return null; // can happen e.g. due to permission errors
300
- }
301
- }));
302
- // make sure to get rid of null values that signal a failure to resolve a particular entry
303
- fileStat.children = resolvedEntries.filter(e => !!e);
304
- }
305
- catch (error) {
306
- console.trace(error);
307
- fileStat.children = []; // gracefully handle errors, we may not have permissions to read
308
- }
309
- return fileStat;
310
- }
311
- return fileStat;
312
- }
313
- async resolveAll(toResolve) {
314
- return Promise.all(toResolve.map(async (entry) => {
315
- try {
316
- return { stat: await this.doResolveFile(entry.resource, entry.options), success: true };
317
- }
318
- catch (error) {
319
- console.trace(error);
320
- return { stat: undefined, success: false };
321
- }
322
- }));
323
- }
324
- /**
325
- * Tests if the given resource exists in the filesystem.
326
- * @param resource `URI` of the resource which should be tested.
327
- * @throws Will throw an error if no {@link FileSystemProvider} is registered for the given resource.
328
- *
329
- * @returns A promise that resolves to `true` if the resource exists.
330
- */
331
- async exists(resource) {
332
- const provider = await this.withProvider(resource);
333
- try {
334
- const stat = await provider.stat(resource);
335
- return !!stat;
336
- }
337
- catch (error) {
338
- return false;
339
- }
340
- }
341
- /**
342
- * Tests a user's permissions for the given resource.
343
- * @param resource `URI` of the resource which should be tested.
344
- * @param mode An optional integer that specifies the accessibility checks to be performed.
345
- * Check `FileAccess.Constants` for possible values of mode.
346
- * It is possible to create a mask consisting of the bitwise `OR` of two or more values (e.g. FileAccess.Constants.W_OK | FileAccess.Constants.R_OK).
347
- * If `mode` is not defined, `FileAccess.Constants.F_OK` will be used instead.
348
- */
349
- async access(resource, mode) {
350
- const provider = await this.withProvider(resource);
351
- if (!(0, files_1.hasAccessCapability)(provider)) {
352
- return false;
353
- }
354
- try {
355
- await provider.access(resource, mode);
356
- return true;
357
- }
358
- catch (error) {
359
- return false;
360
- }
361
- }
362
- /**
363
- * Resolves the fs path of the given URI.
364
- *
365
- * USE WITH CAUTION: You should always prefer URIs to paths if possible, as they are
366
- * portable and platform independent. Paths should only be used in cases you directly
367
- * interact with the OS, e.g. when running a command on the shell.
368
- *
369
- * If you need to display human readable simple or long names then use `LabelProvider` instead.
370
- * @param resource `URI` of the resource that should be resolved.
371
- * @throws Will throw an error if no {@link FileSystemProvider} is registered for the given resource.
372
- *
373
- * @returns A promise of the resolved fs path.
374
- */
375
- async fsPath(resource) {
376
- const provider = await this.withProvider(resource);
377
- if (!(0, files_1.hasAccessCapability)(provider)) {
378
- return resource.path.toString();
379
- }
380
- return provider.fsPath(resource);
381
- }
382
- // #region Text File Reading/Writing
383
- async create(resource, value, options) {
384
- if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
385
- return this.doCreate(resource, value, options);
386
- }
387
- await this.runFileOperationParticipants(resource, undefined, 0 /* CREATE */);
388
- const event = { correlationId: this.correlationIds++, operation: 0 /* CREATE */, target: resource };
389
- await this.onWillRunUserOperationEmitter.fire(event);
390
- let stat;
391
- try {
392
- stat = await this.doCreate(resource, value, options);
393
- }
394
- catch (error) {
395
- await this.onDidFailUserOperationEmitter.fire(event);
396
- throw error;
397
- }
398
- await this.onDidRunUserOperationEmitter.fire(event);
399
- return stat;
400
- }
401
- async doCreate(resource, value, options) {
402
- const encoding = await this.getWriteEncoding(resource, options);
403
- const encoded = await this.encodingService.encodeStream(value, encoding);
404
- return this.createFile(resource, encoded, options);
405
- }
406
- async write(resource, value, options) {
407
- const encoding = await this.getWriteEncoding(resource, options);
408
- const encoded = await this.encodingService.encodeStream(value, encoding);
409
- return Object.assign(await this.writeFile(resource, encoded, options), { encoding: encoding.encoding });
410
- }
411
- async read(resource, options) {
412
- const [bufferStream, decoder] = await this.doRead(resource, {
413
- ...options,
414
- preferUnbuffered: this.shouldReadUnbuffered(options)
415
- });
416
- return {
417
- ...bufferStream,
418
- encoding: decoder.detected.encoding || encodings_1.UTF8,
419
- value: await (0, stream_1.consumeStream)(decoder.stream, strings => strings.join(''))
420
- };
421
- }
422
- async readStream(resource, options) {
423
- const [bufferStream, decoder] = await this.doRead(resource, options);
424
- return {
425
- ...bufferStream,
426
- encoding: decoder.detected.encoding || encodings_1.UTF8,
427
- value: decoder.stream
428
- };
429
- }
430
- async doRead(resource, options) {
431
- options = this.resolveReadOptions(options);
432
- // read stream raw (either buffered or unbuffered)
433
- let bufferStream;
434
- if (options === null || options === void 0 ? void 0 : options.preferUnbuffered) {
435
- const content = await this.readFile(resource, options);
436
- bufferStream = {
437
- ...content,
438
- value: buffer_1.BinaryBufferReadableStream.fromBuffer(content.value)
439
- };
440
- }
441
- else {
442
- bufferStream = await this.readFileStream(resource, options);
443
- }
444
- const decoder = await this.encodingService.decodeStream(bufferStream.value, {
445
- guessEncoding: options.autoGuessEncoding,
446
- overwriteEncoding: detectedEncoding => this.getReadEncoding(resource, options, detectedEncoding)
447
- });
448
- // validate binary
449
- if ((options === null || options === void 0 ? void 0 : options.acceptTextOnly) && decoder.detected.seemsBinary) {
450
- throw new TextFileOperationError(core_1.nls.localizeByDefault('File seems to be binary and cannot be opened as text'), 0 /* FILE_IS_BINARY */, options);
451
- }
452
- return [bufferStream, decoder];
453
- }
454
- resolveReadOptions(options) {
455
- options = {
456
- ...options,
457
- autoGuessEncoding: typeof (options === null || options === void 0 ? void 0 : options.autoGuessEncoding) === 'boolean' ? options.autoGuessEncoding : this.preferences['files.autoGuessEncoding']
458
- };
459
- const limits = options.limits = options.limits || {};
460
- if (typeof limits.size !== 'number') {
461
- limits.size = this.preferences['files.maxFileSizeMB'] * 1024 * 1024;
462
- }
463
- return options;
464
- }
465
- async update(resource, changes, options) {
466
- const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource);
467
- try {
468
- await this.validateWriteFile(provider, resource, options);
469
- if ((0, files_1.hasUpdateCapability)(provider)) {
470
- const encoding = await this.getEncodingForResource(resource, options ? options.encoding : undefined);
471
- ;
472
- const stat = await provider.updateFile(resource, changes, {
473
- readEncoding: options.readEncoding,
474
- writeEncoding: encoding,
475
- overwriteEncoding: options.overwriteEncoding || false
476
- });
477
- return Object.assign(files_1.FileStat.fromStat(resource, stat), { encoding: stat.encoding });
478
- }
479
- else {
480
- throw new Error('incremental file update is not supported');
481
- }
482
- }
483
- catch (error) {
484
- this.rethrowAsFileOperationError("Unable to write file '{0}' ({1})", resource, error, options);
485
- }
486
- }
487
- // #endregion
488
- // #region File Reading/Writing
489
- async createFile(resource, bufferOrReadableOrStream = buffer_1.BinaryBuffer.fromString(''), options) {
490
- // validate overwrite
491
- if (!(options === null || options === void 0 ? void 0 : options.overwrite) && await this.exists(resource)) {
492
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to create file '{0}' that already exists when overwrite flag is not set", this.resourceForError(resource)), 3 /* FILE_MODIFIED_SINCE */, options);
493
- }
494
- // do write into file (this will create it too)
495
- const fileStat = await this.writeFile(resource, bufferOrReadableOrStream);
496
- // events
497
- this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(resource, 0 /* CREATE */, fileStat));
498
- return fileStat;
499
- }
500
- async writeFile(resource, bufferOrReadableOrStream, options) {
501
- const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource);
502
- try {
503
- // validate write
504
- const stat = await this.validateWriteFile(provider, resource, options);
505
- // mkdir recursively as needed
506
- if (!stat) {
507
- await this.mkdirp(provider, resource.parent);
508
- }
509
- // optimization: if the provider has unbuffered write capability and the data
510
- // to write is a Readable, we consume up to 3 chunks and try to write the data
511
- // unbuffered to reduce the overhead. If the Readable has more data to provide
512
- // we continue to write buffered.
513
- let bufferOrReadableOrStreamOrBufferedStream;
514
- if ((0, files_1.hasReadWriteCapability)(provider) && !(bufferOrReadableOrStream instanceof buffer_1.BinaryBuffer)) {
515
- if ((0, stream_1.isReadableStream)(bufferOrReadableOrStream)) {
516
- const bufferedStream = await (0, stream_1.peekStream)(bufferOrReadableOrStream, 3);
517
- if (bufferedStream.ended) {
518
- bufferOrReadableOrStreamOrBufferedStream = buffer_1.BinaryBuffer.concat(bufferedStream.buffer);
519
- }
520
- else {
521
- bufferOrReadableOrStreamOrBufferedStream = bufferedStream;
522
- }
523
- }
524
- else {
525
- bufferOrReadableOrStreamOrBufferedStream = (0, stream_1.peekReadable)(bufferOrReadableOrStream, data => buffer_1.BinaryBuffer.concat(data), 3);
526
- }
527
- }
528
- else {
529
- bufferOrReadableOrStreamOrBufferedStream = bufferOrReadableOrStream;
530
- }
531
- // write file: unbuffered (only if data to write is a buffer, or the provider has no buffered write capability)
532
- if (!(0, files_1.hasOpenReadWriteCloseCapability)(provider) || ((0, files_1.hasReadWriteCapability)(provider) && bufferOrReadableOrStreamOrBufferedStream instanceof buffer_1.BinaryBuffer)) {
533
- await this.doWriteUnbuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream);
534
- }
535
- // write file: buffered
536
- else {
537
- await this.doWriteBuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream instanceof buffer_1.BinaryBuffer ? buffer_1.BinaryBufferReadable.fromBuffer(bufferOrReadableOrStreamOrBufferedStream) : bufferOrReadableOrStreamOrBufferedStream);
538
- }
539
- }
540
- catch (error) {
541
- this.rethrowAsFileOperationError("Unable to write file '{0}' ({1})", resource, error, options);
542
- }
543
- return this.resolve(resource, { resolveMetadata: true });
544
- }
545
- async validateWriteFile(provider, resource, options) {
546
- let stat = undefined;
547
- try {
548
- stat = await provider.stat(resource);
549
- }
550
- catch (error) {
551
- return undefined; // file might not exist
552
- }
553
- // file cannot be directory
554
- if ((stat.type & files_1.FileType.Directory) !== 0) {
555
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to write file '{0}' that is actually a directory", this.resourceForError(resource)), 0 /* FILE_IS_DIRECTORY */, options);
556
- }
557
- if (this.modifiedSince(stat, options)) {
558
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault('File Modified Since'), 3 /* FILE_MODIFIED_SINCE */, options);
559
- }
560
- return stat;
561
- }
562
- /**
563
- * Dirty write prevention: if the file on disk has been changed and does not match our expected
564
- * mtime and etag, we bail out to prevent dirty writing.
565
- *
566
- * First, we check for a mtime that is in the future before we do more checks. The assumption is
567
- * that only the mtime is an indicator for a file that has changed on disk.
568
- *
569
- * Second, if the mtime has advanced, we compare the size of the file on disk with our previous
570
- * one using the etag() function. Relying only on the mtime check has proven to produce false
571
- * positives due to file system weirdness (especially around remote file systems). As such, the
572
- * check for size is a weaker check because it can return a false negative if the file has changed
573
- * but to the same length. This is a compromise we take to avoid having to produce checksums of
574
- * the file content for comparison which would be much slower to compute.
575
- */
576
- modifiedSince(stat, options) {
577
- return !!options && typeof options.mtime === 'number' && typeof options.etag === 'string' && options.etag !== files_1.ETAG_DISABLED &&
578
- typeof stat.mtime === 'number' && typeof stat.size === 'number' &&
579
- options.mtime < stat.mtime && options.etag !== (0, files_1.etag)({ mtime: options.mtime /* not using stat.mtime for a reason, see above */, size: stat.size });
580
- }
581
- shouldReadUnbuffered(options) {
582
- // optimization: since we know that the caller does not
583
- // care about buffering, we indicate this to the reader.
584
- // this reduces all the overhead the buffered reading
585
- // has (open, read, close) if the provider supports
586
- // unbuffered reading.
587
- //
588
- // However, if we read only part of the file we still
589
- // want buffered reading as otherwise we need to read
590
- // the whole file and cut out the specified part later.
591
- return (options === null || options === void 0 ? void 0 : options.position) === undefined && (options === null || options === void 0 ? void 0 : options.length) === undefined;
592
- }
593
- async readFile(resource, options) {
594
- const provider = await this.withReadProvider(resource);
595
- const stream = await this.doReadAsFileStream(provider, resource, {
596
- ...options,
597
- preferUnbuffered: this.shouldReadUnbuffered(options)
598
- });
599
- return {
600
- ...stream,
601
- value: await buffer_1.BinaryBufferReadableStream.toBuffer(stream.value)
602
- };
603
- }
604
- async readFileStream(resource, options) {
605
- const provider = await this.withReadProvider(resource);
606
- return this.doReadAsFileStream(provider, resource, options);
607
- }
608
- async doReadAsFileStream(provider, resource, options) {
609
- // install a cancellation token that gets cancelled
610
- // when any error occurs. this allows us to resolve
611
- // the content of the file while resolving metadata
612
- // but still cancel the operation in certain cases.
613
- const cancellableSource = new cancellation_1.CancellationTokenSource();
614
- // validate read operation
615
- const statPromise = this.validateReadFile(resource, options).then(stat => stat, error => {
616
- cancellableSource.cancel();
617
- throw error;
618
- });
619
- try {
620
- // if the etag is provided, we await the result of the validation
621
- // due to the likelyhood of hitting a NOT_MODIFIED_SINCE result.
622
- // otherwise, we let it run in parallel to the file reading for
623
- // optimal startup performance.
624
- if (options && typeof options.etag === 'string' && options.etag !== files_1.ETAG_DISABLED) {
625
- await statPromise;
626
- }
627
- let fileStreamPromise;
628
- // read unbuffered (only if either preferred, or the provider has no buffered read capability)
629
- if (!((0, files_1.hasOpenReadWriteCloseCapability)(provider) || (0, files_1.hasFileReadStreamCapability)(provider)) || ((0, files_1.hasReadWriteCapability)(provider) && (options === null || options === void 0 ? void 0 : options.preferUnbuffered))) {
630
- fileStreamPromise = this.readFileUnbuffered(provider, resource, options);
631
- }
632
- // read streamed (always prefer over primitive buffered read)
633
- else if ((0, files_1.hasFileReadStreamCapability)(provider)) {
634
- fileStreamPromise = Promise.resolve(this.readFileStreamed(provider, resource, cancellableSource.token, options));
635
- }
636
- // read buffered
637
- else {
638
- fileStreamPromise = Promise.resolve(this.readFileBuffered(provider, resource, cancellableSource.token, options));
639
- }
640
- const [fileStat, fileStream] = await Promise.all([statPromise, fileStreamPromise]);
641
- return {
642
- ...fileStat,
643
- value: fileStream
644
- };
645
- }
646
- catch (error) {
647
- this.rethrowAsFileOperationError("Unable to read file '{0}' ({1})", resource, error, options);
648
- }
649
- }
650
- readFileStreamed(provider, resource, token, options = Object.create(null)) {
651
- const fileStream = provider.readFileStream(resource, options, token);
652
- return (0, stream_1.transform)(fileStream, {
653
- data: data => data instanceof buffer_1.BinaryBuffer ? data : buffer_1.BinaryBuffer.wrap(data),
654
- error: error => this.asFileOperationError("Unable to read file '{0}' ({1})", resource, error, options)
655
- }, data => buffer_1.BinaryBuffer.concat(data));
656
- }
657
- readFileBuffered(provider, resource, token, options = Object.create(null)) {
658
- const stream = buffer_1.BinaryBufferWriteableStream.create();
659
- (0, io_1.readFileIntoStream)(provider, resource, stream, data => data, {
660
- ...options,
661
- bufferSize: this.BUFFER_SIZE,
662
- errorTransformer: error => this.asFileOperationError("Unable to read file '{0}' ({1})", resource, error, options)
663
- }, token);
664
- return stream;
665
- }
666
- rethrowAsFileOperationError(message, resource, error, options) {
667
- throw this.asFileOperationError(message, resource, error, options);
668
- }
669
- asFileOperationError(message, resource, error, options) {
670
- const fileOperationError = new files_1.FileOperationError(core_1.nls.localizeByDefault(message, this.resourceForError(resource), (0, files_1.ensureFileSystemProviderError)(error).toString()), (0, files_1.toFileOperationResult)(error), options);
671
- fileOperationError.stack = `${fileOperationError.stack}\nCaused by: ${error.stack}`;
672
- return fileOperationError;
673
- }
674
- async readFileUnbuffered(provider, resource, options) {
675
- let buffer = await provider.readFile(resource);
676
- // respect position option
677
- if (options && typeof options.position === 'number') {
678
- buffer = buffer.slice(options.position);
679
- }
680
- // respect length option
681
- if (options && typeof options.length === 'number') {
682
- buffer = buffer.slice(0, options.length);
683
- }
684
- // Throw if file is too large to load
685
- this.validateReadFileLimits(resource, buffer.byteLength, options);
686
- return buffer_1.BinaryBufferReadableStream.fromBuffer(buffer_1.BinaryBuffer.wrap(buffer));
687
- }
688
- async validateReadFile(resource, options) {
689
- const stat = await this.resolve(resource, { resolveMetadata: true });
690
- // Throw if resource is a directory
691
- if (stat.isDirectory) {
692
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to read file '{0}' that is actually a directory", this.resourceForError(resource)), 0 /* FILE_IS_DIRECTORY */, options);
693
- }
694
- // Throw if file not modified since (unless disabled)
695
- if (options && typeof options.etag === 'string' && options.etag !== files_1.ETAG_DISABLED && options.etag === stat.etag) {
696
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault('File not modified since'), 2 /* FILE_NOT_MODIFIED_SINCE */, options);
697
- }
698
- // Throw if file is too large to load
699
- this.validateReadFileLimits(resource, stat.size, options);
700
- return stat;
701
- }
702
- validateReadFileLimits(resource, size, options) {
703
- if (options === null || options === void 0 ? void 0 : options.limits) {
704
- let tooLargeErrorResult = undefined;
705
- if (typeof options.limits.memory === 'number' && size > options.limits.memory) {
706
- tooLargeErrorResult = 9 /* FILE_EXCEEDS_MEMORY_LIMIT */;
707
- }
708
- if (typeof options.limits.size === 'number' && size > options.limits.size) {
709
- tooLargeErrorResult = 7 /* FILE_TOO_LARGE */;
710
- }
711
- if (typeof tooLargeErrorResult === 'number') {
712
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to read file '{0}' that is too large to open", this.resourceForError(resource)), tooLargeErrorResult);
713
- }
714
- }
715
- }
716
- // #endregion
717
- // #region Move/Copy/Delete/Create Folder
718
- async move(source, target, options) {
719
- if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
720
- return this.doMove(source, target, options.overwrite);
721
- }
722
- await this.runFileOperationParticipants(target, source, 2 /* MOVE */);
723
- const event = { correlationId: this.correlationIds++, operation: 2 /* MOVE */, target, source };
724
- await this.onWillRunUserOperationEmitter.fire(event);
725
- let stat;
726
- try {
727
- stat = await this.doMove(source, target, options === null || options === void 0 ? void 0 : options.overwrite);
728
- }
729
- catch (error) {
730
- await this.onDidFailUserOperationEmitter.fire(event);
731
- throw error;
732
- }
733
- await this.onDidRunUserOperationEmitter.fire(event);
734
- return stat;
735
- }
736
- async doMove(source, target, overwrite) {
737
- const sourceProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(source), source);
738
- const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
739
- // move
740
- const mode = await this.doMoveCopy(sourceProvider, source, targetProvider, target, 'move', !!overwrite);
741
- // resolve and send events
742
- const fileStat = await this.resolve(target, { resolveMetadata: true });
743
- this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(source, mode === 'move' ? 2 /* MOVE */ : 3 /* COPY */, fileStat));
744
- return fileStat;
745
- }
746
- async copy(source, target, options) {
747
- if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
748
- return this.doCopy(source, target, options.overwrite);
749
- }
750
- await this.runFileOperationParticipants(target, source, 3 /* COPY */);
751
- const event = { correlationId: this.correlationIds++, operation: 3 /* COPY */, target, source };
752
- await this.onWillRunUserOperationEmitter.fire(event);
753
- let stat;
754
- try {
755
- stat = await this.doCopy(source, target, options === null || options === void 0 ? void 0 : options.overwrite);
756
- }
757
- catch (error) {
758
- await this.onDidFailUserOperationEmitter.fire(event);
759
- throw error;
760
- }
761
- await this.onDidRunUserOperationEmitter.fire(event);
762
- return stat;
763
- }
764
- async doCopy(source, target, overwrite) {
765
- const sourceProvider = await this.withReadProvider(source);
766
- const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
767
- // copy
768
- const mode = await this.doMoveCopy(sourceProvider, source, targetProvider, target, 'copy', !!overwrite);
769
- // resolve and send events
770
- const fileStat = await this.resolve(target, { resolveMetadata: true });
771
- this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(source, mode === 'copy' ? 3 /* COPY */ : 2 /* MOVE */, fileStat));
772
- return fileStat;
773
- }
774
- async doMoveCopy(sourceProvider, source, targetProvider, target, mode, overwrite) {
775
- if (source.toString() === target.toString()) {
776
- return mode; // simulate node.js behaviour here and do a no-op if paths match
777
- }
778
- // validation
779
- const { exists, isSameResourceWithDifferentPathCase } = await this.doValidateMoveCopy(sourceProvider, source, targetProvider, target, mode, overwrite);
780
- // if target exists get valid target
781
- if (exists && !overwrite) {
782
- const parent = await this.resolve(target.parent);
783
- const targetFileStat = await this.resolve(target);
784
- target = filesystem_utils_1.FileSystemUtils.generateUniqueResourceURI(parent, target, targetFileStat.isDirectory, isSameResourceWithDifferentPathCase ? 'copy' : undefined);
785
- }
786
- // delete as needed (unless target is same resource with different path case)
787
- if (exists && !isSameResourceWithDifferentPathCase && overwrite) {
788
- await this.delete(target, { recursive: true });
789
- }
790
- // create parent folders
791
- await this.mkdirp(targetProvider, target.parent);
792
- // copy source => target
793
- if (mode === 'copy') {
794
- // same provider with fast copy: leverage copy() functionality
795
- if (sourceProvider === targetProvider && (0, files_1.hasFileFolderCopyCapability)(sourceProvider)) {
796
- await sourceProvider.copy(source, target, { overwrite });
797
- }
798
- // when copying via buffer/unbuffered, we have to manually
799
- // traverse the source if it is a folder and not a file
800
- else {
801
- const sourceFile = await this.resolve(source);
802
- if (sourceFile.isDirectory) {
803
- await this.doCopyFolder(sourceProvider, sourceFile, targetProvider, target);
804
- }
805
- else {
806
- await this.doCopyFile(sourceProvider, source, targetProvider, target);
807
- }
808
- }
809
- return mode;
810
- }
811
- // move source => target
812
- else {
813
- // same provider: leverage rename() functionality
814
- if (sourceProvider === targetProvider) {
815
- await sourceProvider.rename(source, target, { overwrite });
816
- return mode;
817
- }
818
- // across providers: copy to target & delete at source
819
- else {
820
- await this.doMoveCopy(sourceProvider, source, targetProvider, target, 'copy', overwrite);
821
- await this.delete(source, { recursive: true });
822
- return 'copy';
823
- }
824
- }
825
- }
826
- async doCopyFile(sourceProvider, source, targetProvider, target) {
827
- // copy: source (buffered) => target (buffered)
828
- if ((0, files_1.hasOpenReadWriteCloseCapability)(sourceProvider) && (0, files_1.hasOpenReadWriteCloseCapability)(targetProvider)) {
829
- return this.doPipeBuffered(sourceProvider, source, targetProvider, target);
830
- }
831
- // copy: source (buffered) => target (unbuffered)
832
- if ((0, files_1.hasOpenReadWriteCloseCapability)(sourceProvider) && (0, files_1.hasReadWriteCapability)(targetProvider)) {
833
- return this.doPipeBufferedToUnbuffered(sourceProvider, source, targetProvider, target);
834
- }
835
- // copy: source (unbuffered) => target (buffered)
836
- if ((0, files_1.hasReadWriteCapability)(sourceProvider) && (0, files_1.hasOpenReadWriteCloseCapability)(targetProvider)) {
837
- return this.doPipeUnbufferedToBuffered(sourceProvider, source, targetProvider, target);
838
- }
839
- // copy: source (unbuffered) => target (unbuffered)
840
- if ((0, files_1.hasReadWriteCapability)(sourceProvider) && (0, files_1.hasReadWriteCapability)(targetProvider)) {
841
- return this.doPipeUnbuffered(sourceProvider, source, targetProvider, target);
842
- }
843
- }
844
- async doCopyFolder(sourceProvider, sourceFolder, targetProvider, targetFolder) {
845
- // create folder in target
846
- await targetProvider.mkdir(targetFolder);
847
- // create children in target
848
- if (Array.isArray(sourceFolder.children)) {
849
- await Promise.all(sourceFolder.children.map(async (sourceChild) => {
850
- const targetChild = targetFolder.resolve(sourceChild.name);
851
- if (sourceChild.isDirectory) {
852
- return this.doCopyFolder(sourceProvider, await this.resolve(sourceChild.resource), targetProvider, targetChild);
853
- }
854
- else {
855
- return this.doCopyFile(sourceProvider, sourceChild.resource, targetProvider, targetChild);
856
- }
857
- }));
858
- }
859
- }
860
- async doValidateMoveCopy(sourceProvider, source, targetProvider, target, mode, overwrite) {
861
- let isSameResourceWithDifferentPathCase = false;
862
- // Check if source is equal or parent to target (requires providers to be the same)
863
- if (sourceProvider === targetProvider) {
864
- const isPathCaseSensitive = !!(sourceProvider.capabilities & 1024 /* PathCaseSensitive */);
865
- if (!isPathCaseSensitive) {
866
- isSameResourceWithDifferentPathCase = source.toString().toLowerCase() === target.toString().toLowerCase();
867
- }
868
- if (isSameResourceWithDifferentPathCase && mode === 'copy') {
869
- throw new Error(core_1.nls.localizeByDefault("Unable to move/copy when source '{0}' is parent of target '{1}'.", this.resourceForError(source), this.resourceForError(target)));
870
- }
871
- if (!isSameResourceWithDifferentPathCase && target.isEqualOrParent(source, isPathCaseSensitive)) {
872
- throw new Error(core_1.nls.localizeByDefault("Unable to move/copy when source '{0}' is parent of target '{1}'.", this.resourceForError(source), this.resourceForError(target)));
873
- }
874
- }
875
- // Extra checks if target exists and this is not a rename
876
- const exists = await this.exists(target);
877
- if (exists && !isSameResourceWithDifferentPathCase) {
878
- // Special case: if the target is a parent of the source, we cannot delete
879
- // it as it would delete the source as well. In this case we have to throw
880
- if (sourceProvider === targetProvider) {
881
- const isPathCaseSensitive = !!(sourceProvider.capabilities & 1024 /* PathCaseSensitive */);
882
- if (source.isEqualOrParent(target, isPathCaseSensitive)) {
883
- throw new Error(core_1.nls.localizeByDefault("Unable to move/copy '{0}' into '{1}' since a file would replace the folder it is contained in.", this.resourceForError(source), this.resourceForError(target)));
884
- }
885
- }
886
- }
887
- return { exists, isSameResourceWithDifferentPathCase };
888
- }
889
- async createFolder(resource, options = {}) {
890
- const { fromUserGesture = true, } = options;
891
- const provider = this.throwIfFileSystemIsReadonly(await this.withProvider(resource), resource);
892
- // mkdir recursively
893
- await this.mkdirp(provider, resource);
894
- // events
895
- const fileStat = await this.resolve(resource, { resolveMetadata: true });
896
- if (fromUserGesture) {
897
- this.onDidRunUserOperationEmitter.fire({ correlationId: this.correlationIds++, operation: 0 /* CREATE */, target: resource });
898
- }
899
- else {
900
- this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(resource, 0 /* CREATE */, fileStat));
901
- }
902
- return fileStat;
903
- }
904
- async mkdirp(provider, directory) {
905
- const directoriesToCreate = [];
906
- // mkdir until we reach root
907
- while (!directory.path.isRoot) {
908
- try {
909
- const stat = await provider.stat(directory);
910
- if ((stat.type & files_1.FileType.Directory) === 0) {
911
- throw new Error(core_1.nls.localizeByDefault("Unable to create folder '{0}' that already exists but is not a directory", this.resourceForError(directory)));
912
- }
913
- break; // we have hit a directory that exists -> good
914
- }
915
- catch (error) {
916
- // Bubble up any other error that is not file not found
917
- if ((0, files_1.toFileSystemProviderErrorCode)(error) !== files_1.FileSystemProviderErrorCode.FileNotFound) {
918
- throw error;
919
- }
920
- // Upon error, remember directories that need to be created
921
- directoriesToCreate.push(directory.path.base);
922
- // Continue up
923
- directory = directory.parent;
924
- }
925
- }
926
- // Create directories as needed
927
- for (let i = directoriesToCreate.length - 1; i >= 0; i--) {
928
- directory = directory.resolve(directoriesToCreate[i]);
929
- try {
930
- await provider.mkdir(directory);
931
- }
932
- catch (error) {
933
- if ((0, files_1.toFileSystemProviderErrorCode)(error) !== files_1.FileSystemProviderErrorCode.FileExists) {
934
- // For mkdirp() we tolerate that the mkdir() call fails
935
- // in case the folder already exists. This follows node.js
936
- // own implementation of fs.mkdir({ recursive: true }) and
937
- // reduces the chances of race conditions leading to errors
938
- // if multiple calls try to create the same folders
939
- // As such, we only throw an error here if it is other than
940
- // the fact that the file already exists.
941
- // (see also https://github.com/microsoft/vscode/issues/89834)
942
- throw error;
943
- }
944
- }
945
- }
946
- }
947
- async delete(resource, options) {
948
- if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
949
- return this.doDelete(resource, options);
950
- }
951
- await this.runFileOperationParticipants(resource, undefined, 1 /* DELETE */);
952
- const event = { correlationId: this.correlationIds++, operation: 1 /* DELETE */, target: resource };
953
- await this.onWillRunUserOperationEmitter.fire(event);
954
- try {
955
- await this.doDelete(resource, options);
956
- }
957
- catch (error) {
958
- await this.onDidFailUserOperationEmitter.fire(event);
959
- throw error;
960
- }
961
- await this.onDidRunUserOperationEmitter.fire(event);
962
- }
963
- async doDelete(resource, options) {
964
- const provider = this.throwIfFileSystemIsReadonly(await this.withProvider(resource), resource);
965
- // Validate trash support
966
- const useTrash = !!(options === null || options === void 0 ? void 0 : options.useTrash);
967
- if (useTrash && !(provider.capabilities & 4096 /* Trash */)) {
968
- throw new Error(core_1.nls.localizeByDefault("Unable to delete file '{0}' via trash because provider does not support it.", this.resourceForError(resource)));
969
- }
970
- // Validate delete
971
- const exists = await this.exists(resource);
972
- if (!exists) {
973
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to delete nonexistent file '{0}'", this.resourceForError(resource)), 1 /* FILE_NOT_FOUND */);
974
- }
975
- // Validate recursive
976
- const recursive = !!(options === null || options === void 0 ? void 0 : options.recursive);
977
- if (!recursive && exists) {
978
- const stat = await this.resolve(resource);
979
- if (stat.isDirectory && Array.isArray(stat.children) && stat.children.length > 0) {
980
- throw new Error(core_1.nls.localizeByDefault("Unable to delete non-empty folder '{0}'.", this.resourceForError(resource)));
981
- }
982
- }
983
- // Delete through provider
984
- await provider.delete(resource, { recursive, useTrash });
985
- // Events
986
- this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(resource, 1 /* DELETE */));
987
- }
988
- /**
989
- * An event that is emitted when files are changed on the disk.
990
- */
991
- get onDidFilesChange() {
992
- return this.onDidFilesChangeEmitter.event;
993
- }
994
- watch(resource, options = { recursive: false, excludes: [] }) {
995
- const resolvedOptions = {
996
- ...options,
997
- // always ignore temporary upload files
998
- excludes: options.excludes.concat('**/theia_upload_*')
999
- };
1000
- let watchDisposed = false;
1001
- let watchDisposable = disposable_1.Disposable.create(() => watchDisposed = true);
1002
- // Watch and wire in disposable which is async but
1003
- // check if we got disposed meanwhile and forward
1004
- this.doWatch(resource, resolvedOptions).then(disposable => {
1005
- if (watchDisposed) {
1006
- disposable.dispose();
1007
- }
1008
- else {
1009
- watchDisposable = disposable;
1010
- }
1011
- }, error => console.error(error));
1012
- return disposable_1.Disposable.create(() => watchDisposable.dispose());
1013
- }
1014
- async doWatch(resource, options) {
1015
- const provider = await this.withProvider(resource);
1016
- const key = this.toWatchKey(provider, resource, options);
1017
- // Only start watching if we are the first for the given key
1018
- const watcher = this.activeWatchers.get(key) || { count: 0, disposable: provider.watch(resource, options) };
1019
- if (!this.activeWatchers.has(key)) {
1020
- this.activeWatchers.set(key, watcher);
1021
- }
1022
- // Increment usage counter
1023
- watcher.count += 1;
1024
- return disposable_1.Disposable.create(() => {
1025
- // Unref
1026
- watcher.count--;
1027
- // Dispose only when last user is reached
1028
- if (watcher.count === 0) {
1029
- watcher.disposable.dispose();
1030
- this.activeWatchers.delete(key);
1031
- }
1032
- });
1033
- }
1034
- toWatchKey(provider, resource, options) {
1035
- return [
1036
- this.toMapKey(provider, resource),
1037
- String(options.recursive),
1038
- options.excludes.join() // use excludes as part of the key
1039
- ].join();
1040
- }
1041
- ensureWriteQueue(provider, resource, task) {
1042
- // ensure to never write to the same resource without finishing
1043
- // the one write. this ensures a write finishes consistently
1044
- // (even with error) before another write is done.
1045
- const queueKey = this.toMapKey(provider, resource);
1046
- const writeQueue = (this.writeQueues.get(queueKey) || Promise.resolve()).then(task, task);
1047
- this.writeQueues.set(queueKey, writeQueue);
1048
- return writeQueue;
1049
- }
1050
- toMapKey(provider, resource) {
1051
- const isPathCaseSensitive = !!(provider.capabilities & 1024 /* PathCaseSensitive */);
1052
- return isPathCaseSensitive ? resource.toString() : resource.toString().toLowerCase();
1053
- }
1054
- async doWriteBuffered(provider, resource, readableOrStreamOrBufferedStream) {
1055
- return this.ensureWriteQueue(provider, resource, async () => {
1056
- // open handle
1057
- const handle = await provider.open(resource, { create: true });
1058
- // write into handle until all bytes from buffer have been written
1059
- try {
1060
- if ((0, stream_1.isReadableStream)(readableOrStreamOrBufferedStream) || (0, stream_1.isReadableBufferedStream)(readableOrStreamOrBufferedStream)) {
1061
- await this.doWriteStreamBufferedQueued(provider, handle, readableOrStreamOrBufferedStream);
1062
- }
1063
- else {
1064
- await this.doWriteReadableBufferedQueued(provider, handle, readableOrStreamOrBufferedStream);
1065
- }
1066
- }
1067
- catch (error) {
1068
- throw (0, files_1.ensureFileSystemProviderError)(error);
1069
- }
1070
- finally {
1071
- // close handle always
1072
- await provider.close(handle);
1073
- }
1074
- });
1075
- }
1076
- async doWriteStreamBufferedQueued(provider, handle, streamOrBufferedStream) {
1077
- let posInFile = 0;
1078
- let stream;
1079
- // Buffered stream: consume the buffer first by writing
1080
- // it to the target before reading from the stream.
1081
- if ((0, stream_1.isReadableBufferedStream)(streamOrBufferedStream)) {
1082
- if (streamOrBufferedStream.buffer.length > 0) {
1083
- const chunk = buffer_1.BinaryBuffer.concat(streamOrBufferedStream.buffer);
1084
- await this.doWriteBuffer(provider, handle, chunk, chunk.byteLength, posInFile, 0);
1085
- posInFile += chunk.byteLength;
1086
- }
1087
- // If the stream has been consumed, return early
1088
- if (streamOrBufferedStream.ended) {
1089
- return;
1090
- }
1091
- stream = streamOrBufferedStream.stream;
1092
- }
1093
- // Unbuffered stream - just take as is
1094
- else {
1095
- stream = streamOrBufferedStream;
1096
- }
1097
- return new Promise(async (resolve, reject) => {
1098
- stream.on('data', async (chunk) => {
1099
- // pause stream to perform async write operation
1100
- stream.pause();
1101
- try {
1102
- await this.doWriteBuffer(provider, handle, chunk, chunk.byteLength, posInFile, 0);
1103
- }
1104
- catch (error) {
1105
- return reject(error);
1106
- }
1107
- posInFile += chunk.byteLength;
1108
- // resume stream now that we have successfully written
1109
- // run this on the next tick to prevent increasing the
1110
- // execution stack because resume() may call the event
1111
- // handler again before finishing.
1112
- setTimeout(() => stream.resume());
1113
- });
1114
- stream.on('error', error => reject(error));
1115
- stream.on('end', () => resolve());
1116
- });
1117
- }
1118
- async doWriteReadableBufferedQueued(provider, handle, readable) {
1119
- let posInFile = 0;
1120
- let chunk;
1121
- while ((chunk = readable.read()) !== null) {
1122
- await this.doWriteBuffer(provider, handle, chunk, chunk.byteLength, posInFile, 0);
1123
- posInFile += chunk.byteLength;
1124
- }
1125
- }
1126
- async doWriteBuffer(provider, handle, buffer, length, posInFile, posInBuffer) {
1127
- let totalBytesWritten = 0;
1128
- while (totalBytesWritten < length) {
1129
- const bytesWritten = await provider.write(handle, posInFile + totalBytesWritten, buffer.buffer, posInBuffer + totalBytesWritten, length - totalBytesWritten);
1130
- totalBytesWritten += bytesWritten;
1131
- }
1132
- }
1133
- async doWriteUnbuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream) {
1134
- return this.ensureWriteQueue(provider, resource, () => this.doWriteUnbufferedQueued(provider, resource, bufferOrReadableOrStreamOrBufferedStream));
1135
- }
1136
- async doWriteUnbufferedQueued(provider, resource, bufferOrReadableOrStreamOrBufferedStream) {
1137
- let buffer;
1138
- if (bufferOrReadableOrStreamOrBufferedStream instanceof buffer_1.BinaryBuffer) {
1139
- buffer = bufferOrReadableOrStreamOrBufferedStream;
1140
- }
1141
- else if ((0, stream_1.isReadableStream)(bufferOrReadableOrStreamOrBufferedStream)) {
1142
- buffer = await buffer_1.BinaryBufferReadableStream.toBuffer(bufferOrReadableOrStreamOrBufferedStream);
1143
- }
1144
- else if ((0, stream_1.isReadableBufferedStream)(bufferOrReadableOrStreamOrBufferedStream)) {
1145
- buffer = await buffer_1.BinaryBufferReadableBufferedStream.toBuffer(bufferOrReadableOrStreamOrBufferedStream);
1146
- }
1147
- else {
1148
- buffer = buffer_1.BinaryBufferReadable.toBuffer(bufferOrReadableOrStreamOrBufferedStream);
1149
- }
1150
- return provider.writeFile(resource, buffer.buffer, { create: true, overwrite: true });
1151
- }
1152
- async doPipeBuffered(sourceProvider, source, targetProvider, target) {
1153
- return this.ensureWriteQueue(targetProvider, target, () => this.doPipeBufferedQueued(sourceProvider, source, targetProvider, target));
1154
- }
1155
- async doPipeBufferedQueued(sourceProvider, source, targetProvider, target) {
1156
- let sourceHandle = undefined;
1157
- let targetHandle = undefined;
1158
- try {
1159
- // Open handles
1160
- sourceHandle = await sourceProvider.open(source, { create: false });
1161
- targetHandle = await targetProvider.open(target, { create: true });
1162
- const buffer = buffer_1.BinaryBuffer.alloc(this.BUFFER_SIZE);
1163
- let posInFile = 0;
1164
- let posInBuffer = 0;
1165
- let bytesRead = 0;
1166
- do {
1167
- // read from source (sourceHandle) at current position (posInFile) into buffer (buffer) at
1168
- // buffer position (posInBuffer) up to the size of the buffer (buffer.byteLength).
1169
- bytesRead = await sourceProvider.read(sourceHandle, posInFile, buffer.buffer, posInBuffer, buffer.byteLength - posInBuffer);
1170
- // write into target (targetHandle) at current position (posInFile) from buffer (buffer) at
1171
- // buffer position (posInBuffer) all bytes we read (bytesRead).
1172
- await this.doWriteBuffer(targetProvider, targetHandle, buffer, bytesRead, posInFile, posInBuffer);
1173
- posInFile += bytesRead;
1174
- posInBuffer += bytesRead;
1175
- // when buffer full, fill it again from the beginning
1176
- if (posInBuffer === buffer.byteLength) {
1177
- posInBuffer = 0;
1178
- }
1179
- } while (bytesRead > 0);
1180
- }
1181
- catch (error) {
1182
- throw (0, files_1.ensureFileSystemProviderError)(error);
1183
- }
1184
- finally {
1185
- await Promise.all([
1186
- typeof sourceHandle === 'number' ? sourceProvider.close(sourceHandle) : Promise.resolve(),
1187
- typeof targetHandle === 'number' ? targetProvider.close(targetHandle) : Promise.resolve(),
1188
- ]);
1189
- }
1190
- }
1191
- async doPipeUnbuffered(sourceProvider, source, targetProvider, target) {
1192
- return this.ensureWriteQueue(targetProvider, target, () => this.doPipeUnbufferedQueued(sourceProvider, source, targetProvider, target));
1193
- }
1194
- async doPipeUnbufferedQueued(sourceProvider, source, targetProvider, target) {
1195
- return targetProvider.writeFile(target, await sourceProvider.readFile(source), { create: true, overwrite: true });
1196
- }
1197
- async doPipeUnbufferedToBuffered(sourceProvider, source, targetProvider, target) {
1198
- return this.ensureWriteQueue(targetProvider, target, () => this.doPipeUnbufferedToBufferedQueued(sourceProvider, source, targetProvider, target));
1199
- }
1200
- async doPipeUnbufferedToBufferedQueued(sourceProvider, source, targetProvider, target) {
1201
- // Open handle
1202
- const targetHandle = await targetProvider.open(target, { create: true });
1203
- // Read entire buffer from source and write buffered
1204
- try {
1205
- const buffer = await sourceProvider.readFile(source);
1206
- await this.doWriteBuffer(targetProvider, targetHandle, buffer_1.BinaryBuffer.wrap(buffer), buffer.byteLength, 0, 0);
1207
- }
1208
- catch (error) {
1209
- throw (0, files_1.ensureFileSystemProviderError)(error);
1210
- }
1211
- finally {
1212
- await targetProvider.close(targetHandle);
1213
- }
1214
- }
1215
- async doPipeBufferedToUnbuffered(sourceProvider, source, targetProvider, target) {
1216
- // Read buffer via stream buffered
1217
- const buffer = await buffer_1.BinaryBufferReadableStream.toBuffer(this.readFileBuffered(sourceProvider, source, cancellation_1.CancellationToken.None));
1218
- // Write buffer into target at once
1219
- await this.doWriteUnbuffered(targetProvider, target, buffer);
1220
- }
1221
- throwIfFileSystemIsReadonly(provider, resource) {
1222
- if (provider.capabilities & 2048 /* Readonly */) {
1223
- throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to modify read-only file '{0}'", this.resourceForError(resource)), 6 /* FILE_PERMISSION_DENIED */);
1224
- }
1225
- return provider;
1226
- }
1227
- resourceForError(resource) {
1228
- return this.labelProvider.getLongName(resource);
1229
- }
1230
- addFileOperationParticipant(participant) {
1231
- this.participants.push(participant);
1232
- return disposable_1.Disposable.create(() => {
1233
- const index = this.participants.indexOf(participant);
1234
- if (index > -1) {
1235
- this.participants.splice(index, 1);
1236
- }
1237
- });
1238
- }
1239
- async runFileOperationParticipants(target, source, operation) {
1240
- const participantsTimeout = this.preferences['files.participants.timeout'];
1241
- if (participantsTimeout <= 0 || this.participants.length === 0) {
1242
- return;
1243
- }
1244
- const cancellationTokenSource = new cancellation_1.CancellationTokenSource();
1245
- return this.progressService.withProgress(this.progressLabel(operation), 'notification', async () => {
1246
- for (const participant of this.participants) {
1247
- if (cancellationTokenSource.token.isCancellationRequested) {
1248
- break;
1249
- }
1250
- try {
1251
- const promise = participant.participate(target, source, operation, participantsTimeout, cancellationTokenSource.token);
1252
- await Promise.race([
1253
- promise,
1254
- (0, promise_util_1.timeout)(participantsTimeout, cancellationTokenSource.token).then(() => cancellationTokenSource.dispose(), () => { })
1255
- ]);
1256
- }
1257
- catch (err) {
1258
- console.warn(err);
1259
- }
1260
- }
1261
- }, () => {
1262
- cancellationTokenSource.cancel();
1263
- });
1264
- }
1265
- progressLabel(operation) {
1266
- switch (operation) {
1267
- case 0 /* CREATE */:
1268
- return core_1.nls.localizeByDefault("Running 'File Create' participants...");
1269
- case 2 /* MOVE */:
1270
- return core_1.nls.localizeByDefault("Running 'File Rename' participants...");
1271
- case 3 /* COPY */:
1272
- return core_1.nls.localizeByDefault("Running 'File Copy' participants...");
1273
- case 1 /* DELETE */:
1274
- return core_1.nls.localizeByDefault("Running 'File Delete' participants...");
1275
- }
1276
- }
1277
- // #endregion
1278
- // #region encoding
1279
- async getWriteEncoding(resource, options) {
1280
- const encoding = await this.getEncodingForResource(resource, options ? options.encoding : undefined);
1281
- return this.encodingService.toResourceEncoding(encoding, {
1282
- overwriteEncoding: options === null || options === void 0 ? void 0 : options.overwriteEncoding,
1283
- read: async (length) => {
1284
- const buffer = await buffer_1.BinaryBufferReadableStream.toBuffer((await this.readFileStream(resource, { length })).value);
1285
- return buffer.buffer;
1286
- }
1287
- });
1288
- }
1289
- getReadEncoding(resource, options, detectedEncoding) {
1290
- let preferredEncoding;
1291
- // Encoding passed in as option
1292
- if (options === null || options === void 0 ? void 0 : options.encoding) {
1293
- if (detectedEncoding === encodings_1.UTF8_with_bom && options.encoding === encodings_1.UTF8) {
1294
- preferredEncoding = encodings_1.UTF8_with_bom; // indicate the file has BOM if we are to resolve with UTF 8
1295
- }
1296
- else {
1297
- preferredEncoding = options.encoding; // give passed in encoding highest priority
1298
- }
1299
- }
1300
- else if (detectedEncoding) {
1301
- preferredEncoding = detectedEncoding;
1302
- }
1303
- return this.getEncodingForResource(resource, preferredEncoding);
1304
- }
1305
- async getEncodingForResource(resource, preferredEncoding) {
1306
- resource = await this.toUnderlyingResource(resource);
1307
- return this.encodingRegistry.getEncodingForResource(resource, preferredEncoding);
1308
- }
1309
- /**
1310
- * Converts to an underlying fs provider resource format.
1311
- *
1312
- * For example converting `user-storage` resources to `file` resources under a user home:
1313
- * user-storage:/user/settings.json => file://home/.theia/settings.json
1314
- */
1315
- async toUnderlyingResource(resource) {
1316
- let provider = await this.withProvider(resource);
1317
- while (provider instanceof delegating_file_system_provider_1.DelegatingFileSystemProvider) {
1318
- resource = provider.toUnderlyingResource(resource);
1319
- provider = await this.withProvider(resource);
1320
- }
1321
- return resource;
1322
- }
1323
- // #endregion
1324
- handleFileWatchError() {
1325
- this.watcherErrorHandler.handleError();
1326
- }
1327
- };
1328
- (0, tslib_1.__decorate)([
1329
- (0, inversify_1.inject)(label_provider_1.LabelProvider),
1330
- (0, tslib_1.__metadata)("design:type", label_provider_1.LabelProvider)
1331
- ], FileService.prototype, "labelProvider", void 0);
1332
- (0, tslib_1.__decorate)([
1333
- (0, inversify_1.inject)(filesystem_preferences_1.FileSystemPreferences),
1334
- (0, tslib_1.__metadata)("design:type", Object)
1335
- ], FileService.prototype, "preferences", void 0);
1336
- (0, tslib_1.__decorate)([
1337
- (0, inversify_1.inject)(progress_service_1.ProgressService),
1338
- (0, tslib_1.__metadata)("design:type", progress_service_1.ProgressService)
1339
- ], FileService.prototype, "progressService", void 0);
1340
- (0, tslib_1.__decorate)([
1341
- (0, inversify_1.inject)(encoding_registry_1.EncodingRegistry),
1342
- (0, tslib_1.__metadata)("design:type", encoding_registry_1.EncodingRegistry)
1343
- ], FileService.prototype, "encodingRegistry", void 0);
1344
- (0, tslib_1.__decorate)([
1345
- (0, inversify_1.inject)(encoding_service_1.EncodingService),
1346
- (0, tslib_1.__metadata)("design:type", encoding_service_1.EncodingService)
1347
- ], FileService.prototype, "encodingService", void 0);
1348
- (0, tslib_1.__decorate)([
1349
- (0, inversify_1.inject)(contribution_provider_1.ContributionProvider),
1350
- (0, inversify_1.named)(exports.FileServiceContribution),
1351
- (0, tslib_1.__metadata)("design:type", Object)
1352
- ], FileService.prototype, "contributions", void 0);
1353
- (0, tslib_1.__decorate)([
1354
- (0, inversify_1.inject)(filesystem_watcher_error_handler_1.FileSystemWatcherErrorHandler),
1355
- (0, tslib_1.__metadata)("design:type", filesystem_watcher_error_handler_1.FileSystemWatcherErrorHandler)
1356
- ], FileService.prototype, "watcherErrorHandler", void 0);
1357
- (0, tslib_1.__decorate)([
1358
- (0, inversify_1.postConstruct)(),
1359
- (0, tslib_1.__metadata)("design:type", Function),
1360
- (0, tslib_1.__metadata)("design:paramtypes", []),
1361
- (0, tslib_1.__metadata)("design:returntype", void 0)
1362
- ], FileService.prototype, "init", null);
1363
- FileService = (0, tslib_1.__decorate)([
1364
- (0, inversify_1.injectable)()
1365
- ], FileService);
1366
- exports.FileService = FileService;
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/common/fileService.ts
22
+ // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/textfile/browser/textFileService.ts
23
+ // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/textfile/electron-browser/nativeTextFileService.ts
24
+ // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/workingCopy/common/workingCopyFileService.ts
25
+ // and https://github.com/microsoft/vscode/blob/04c36be045a94fee58e5f8992d3e3fd980294a84/src/vs/workbench/services/workingCopy/common/workingCopyFileOperationParticipant.ts
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.FileService = exports.TextFileOperationError = exports.FileServiceContribution = void 0;
28
+ const tslib_1 = require("tslib");
29
+ /* eslint-disable max-len */
30
+ /* eslint-disable @typescript-eslint/no-shadow */
31
+ /* eslint-disable no-null/no-null */
32
+ /* eslint-disable @typescript-eslint/tslint/config */
33
+ /* eslint-disable @typescript-eslint/no-explicit-any */
34
+ const inversify_1 = require("@theia/core/shared/inversify");
35
+ const promise_util_1 = require("@theia/core/lib/common/promise-util");
36
+ const cancellation_1 = require("@theia/core/lib/common/cancellation");
37
+ const disposable_1 = require("@theia/core/lib/common/disposable");
38
+ const event_1 = require("@theia/core/lib/common/event");
39
+ const contribution_provider_1 = require("@theia/core/lib/common/contribution-provider");
40
+ const ternary_search_tree_1 = require("@theia/core/lib/common/ternary-search-tree");
41
+ const files_1 = require("../common/files");
42
+ const buffer_1 = require("@theia/core/lib/common/buffer");
43
+ const stream_1 = require("@theia/core/lib/common/stream");
44
+ const label_provider_1 = require("@theia/core/lib/browser/label-provider");
45
+ const filesystem_preferences_1 = require("./filesystem-preferences");
46
+ const progress_service_1 = require("@theia/core/lib/common/progress-service");
47
+ const delegating_file_system_provider_1 = require("../common/delegating-file-system-provider");
48
+ const encoding_registry_1 = require("@theia/core/lib/browser/encoding-registry");
49
+ const encodings_1 = require("@theia/core/lib/common/encodings");
50
+ const encoding_service_1 = require("@theia/core/lib/common/encoding-service");
51
+ const io_1 = require("../common/io");
52
+ const filesystem_watcher_error_handler_1 = require("./filesystem-watcher-error-handler");
53
+ const filesystem_utils_1 = require("../common/filesystem-utils");
54
+ const core_1 = require("@theia/core");
55
+ exports.FileServiceContribution = Symbol('FileServiceContribution');
56
+ class TextFileOperationError extends files_1.FileOperationError {
57
+ constructor(message, textFileOperationResult, options) {
58
+ super(message, 11 /* FILE_OTHER_ERROR */);
59
+ this.textFileOperationResult = textFileOperationResult;
60
+ this.options = options;
61
+ Object.setPrototypeOf(this, TextFileOperationError.prototype);
62
+ }
63
+ }
64
+ exports.TextFileOperationError = TextFileOperationError;
65
+ /**
66
+ * The {@link FileService} is the common facade responsible for all interactions with file systems.
67
+ * It manages all registered {@link FileSystemProvider}s and
68
+ * forwards calls to the responsible {@link FileSystemProvider}, determined by the scheme.
69
+ * For additional documentation regarding the provided functions see also {@link FileSystemProvider}.
70
+ */
71
+ let FileService = class FileService {
72
+ constructor() {
73
+ this.BUFFER_SIZE = 64 * 1024;
74
+ // #region Events
75
+ this.correlationIds = 0;
76
+ this.onWillRunUserOperationEmitter = new event_1.AsyncEmitter();
77
+ /**
78
+ * An event that is emitted when file operation is being performed.
79
+ * This event is triggered by user gestures.
80
+ */
81
+ this.onWillRunUserOperation = this.onWillRunUserOperationEmitter.event;
82
+ this.onDidFailUserOperationEmitter = new event_1.AsyncEmitter();
83
+ /**
84
+ * An event that is emitted when file operation is failed.
85
+ * This event is triggered by user gestures.
86
+ */
87
+ this.onDidFailUserOperation = this.onDidFailUserOperationEmitter.event;
88
+ this.onDidRunUserOperationEmitter = new event_1.AsyncEmitter();
89
+ /**
90
+ * An event that is emitted when file operation is finished.
91
+ * This event is triggered by user gestures.
92
+ */
93
+ this.onDidRunUserOperation = this.onDidRunUserOperationEmitter.event;
94
+ // #endregion
95
+ // #region File System Provider
96
+ this.onDidChangeFileSystemProviderRegistrationsEmitter = new event_1.Emitter();
97
+ this.onDidChangeFileSystemProviderRegistrations = this.onDidChangeFileSystemProviderRegistrationsEmitter.event;
98
+ this.onWillActivateFileSystemProviderEmitter = new event_1.Emitter();
99
+ /**
100
+ * See `FileServiceContribution.registerProviders`.
101
+ */
102
+ this.onWillActivateFileSystemProvider = this.onWillActivateFileSystemProviderEmitter.event;
103
+ this.onDidChangeFileSystemProviderCapabilitiesEmitter = new event_1.Emitter();
104
+ this.onDidChangeFileSystemProviderCapabilities = this.onDidChangeFileSystemProviderCapabilitiesEmitter.event;
105
+ this.onDidChangeFileSystemProviderReadOnlyMessageEmitter = new event_1.Emitter();
106
+ this.onDidChangeFileSystemProviderReadOnlyMessage = this.onDidChangeFileSystemProviderReadOnlyMessageEmitter.event;
107
+ this.providers = new Map();
108
+ this.activations = new Map();
109
+ // #endregion
110
+ this.onDidRunOperationEmitter = new event_1.Emitter();
111
+ /**
112
+ * An event that is emitted when operation is finished.
113
+ * This event is triggered by user gestures and programmatically.
114
+ */
115
+ this.onDidRunOperation = this.onDidRunOperationEmitter.event;
116
+ // #endregion
117
+ // #region File Watching
118
+ this.onDidFilesChangeEmitter = new event_1.Emitter();
119
+ this.activeWatchers = new Map();
120
+ // #endregion
121
+ // #region Helpers
122
+ this.writeQueues = new Map();
123
+ // #endregion
124
+ // #region File operation participants
125
+ this.participants = [];
126
+ }
127
+ init() {
128
+ for (const contribution of this.contributions.getContributions()) {
129
+ contribution.registerFileSystemProviders(this);
130
+ }
131
+ }
132
+ /**
133
+ * Registers a new {@link FileSystemProvider} for the given scheme.
134
+ * @param scheme The (uri) scheme for which the provider should be registered.
135
+ * @param provider The file system provider that should be registered.
136
+ *
137
+ * @returns A `Disposable` that can be invoked to unregister the given provider.
138
+ */
139
+ registerProvider(scheme, provider) {
140
+ if (this.providers.has(scheme)) {
141
+ throw new Error(`A filesystem provider for the scheme '${scheme}' is already registered.`);
142
+ }
143
+ this.providers.set(scheme, provider);
144
+ this.onDidChangeFileSystemProviderRegistrationsEmitter.fire({ added: true, scheme, provider });
145
+ const providerDisposables = new disposable_1.DisposableCollection();
146
+ providerDisposables.push(provider.onDidChangeFile(changes => this.onDidFilesChangeEmitter.fire(new files_1.FileChangesEvent(changes))));
147
+ providerDisposables.push(provider.onFileWatchError(() => this.handleFileWatchError()));
148
+ providerDisposables.push(provider.onDidChangeCapabilities(() => this.onDidChangeFileSystemProviderCapabilitiesEmitter.fire({ provider, scheme })));
149
+ if (files_1.ReadOnlyMessageFileSystemProvider.is(provider)) {
150
+ providerDisposables.push(provider.onDidChangeReadOnlyMessage(message => this.onDidChangeFileSystemProviderReadOnlyMessageEmitter.fire({ provider, scheme, message })));
151
+ }
152
+ return disposable_1.Disposable.create(() => {
153
+ this.onDidChangeFileSystemProviderRegistrationsEmitter.fire({ added: false, scheme, provider });
154
+ this.providers.delete(scheme);
155
+ providerDisposables.dispose();
156
+ });
157
+ }
158
+ /**
159
+ * Try to activate the registered provider for the given scheme
160
+ * @param scheme The uri scheme for which the responsible provider should be activated.
161
+ *
162
+ * @returns A promise of the activated file system provider. Only resolves if a provider is available for this scheme, gets rejected otherwise.
163
+ */
164
+ async activateProvider(scheme) {
165
+ let provider = this.providers.get(scheme);
166
+ if (provider) {
167
+ return provider;
168
+ }
169
+ let activation = this.activations.get(scheme);
170
+ if (!activation) {
171
+ const deferredActivation = new promise_util_1.Deferred();
172
+ this.activations.set(scheme, activation = deferredActivation.promise);
173
+ event_1.WaitUntilEvent.fire(this.onWillActivateFileSystemProviderEmitter, { scheme }).then(() => {
174
+ provider = this.providers.get(scheme);
175
+ if (!provider) {
176
+ const error = new Error();
177
+ error.name = 'ENOPRO';
178
+ error.message = `No file system provider found for scheme ${scheme}`;
179
+ throw error;
180
+ }
181
+ else {
182
+ deferredActivation.resolve(provider);
183
+ }
184
+ }).catch(e => deferredActivation.reject(e));
185
+ }
186
+ return activation;
187
+ }
188
+ /**
189
+ * Tests if the service (i.e. any of its registered {@link FileSystemProvider}s) can handle the given resource.
190
+ * @param resource `URI` of the resource to test.
191
+ *
192
+ * @returns `true` if the resource can be handled, `false` otherwise.
193
+ */
194
+ canHandleResource(resource) {
195
+ return this.providers.has(resource.scheme);
196
+ }
197
+ getReadOnlyMessage(resource) {
198
+ const provider = this.providers.get(resource.scheme);
199
+ if (files_1.ReadOnlyMessageFileSystemProvider.is(provider)) {
200
+ return provider.readOnlyMessage;
201
+ }
202
+ return undefined;
203
+ }
204
+ /**
205
+ * Tests if the service (i.e the {@link FileSystemProvider} registered for the given uri scheme) provides the given capability.
206
+ * @param resource `URI` of the resource to test.
207
+ * @param capability The required capability.
208
+ *
209
+ * @returns `true` if the resource can be handled and the required capability can be provided.
210
+ */
211
+ hasCapability(resource, capability) {
212
+ const provider = this.providers.get(resource.scheme);
213
+ return !!(provider && (provider.capabilities & capability));
214
+ }
215
+ /**
216
+ * List the schemes and capabilities for registered file system providers
217
+ */
218
+ listCapabilities() {
219
+ return Array.from(this.providers.entries()).map(([scheme, provider]) => ({
220
+ scheme,
221
+ capabilities: provider.capabilities
222
+ }));
223
+ }
224
+ async withProvider(resource) {
225
+ // Assert path is absolute
226
+ if (!resource.path.isAbsolute) {
227
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to resolve filesystem provider with relative file path '{0}'", this.resourceForError(resource)), 8 /* FILE_INVALID_PATH */);
228
+ }
229
+ return this.activateProvider(resource.scheme);
230
+ }
231
+ async withReadProvider(resource) {
232
+ const provider = await this.withProvider(resource);
233
+ if ((0, files_1.hasOpenReadWriteCloseCapability)(provider) || (0, files_1.hasReadWriteCapability)(provider)) {
234
+ return provider;
235
+ }
236
+ throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite, FileReadStream nor FileOpenReadWriteClose capability which is needed for the read operation.`);
237
+ }
238
+ async withWriteProvider(resource) {
239
+ const provider = await this.withProvider(resource);
240
+ if ((0, files_1.hasOpenReadWriteCloseCapability)(provider) || (0, files_1.hasReadWriteCapability)(provider)) {
241
+ return provider;
242
+ }
243
+ throw new Error(`Filesystem provider for scheme '${resource.scheme}' neither has FileReadWrite nor FileOpenReadWriteClose capability which is needed for the write operation.`);
244
+ }
245
+ async resolve(resource, options) {
246
+ try {
247
+ return await this.doResolveFile(resource, options);
248
+ }
249
+ catch (error) {
250
+ // Specially handle file not found case as file operation result
251
+ if ((0, files_1.toFileSystemProviderErrorCode)(error) === files_1.FileSystemProviderErrorCode.FileNotFound) {
252
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to resolve nonexistent file '{0}'", this.resourceForError(resource)), 1 /* FILE_NOT_FOUND */);
253
+ }
254
+ // Bubble up any other error as is
255
+ throw (0, files_1.ensureFileSystemProviderError)(error);
256
+ }
257
+ }
258
+ async doResolveFile(resource, options) {
259
+ const provider = await this.withProvider(resource);
260
+ const resolveTo = options === null || options === void 0 ? void 0 : options.resolveTo;
261
+ const resolveSingleChildDescendants = options === null || options === void 0 ? void 0 : options.resolveSingleChildDescendants;
262
+ const resolveMetadata = options === null || options === void 0 ? void 0 : options.resolveMetadata;
263
+ const stat = await provider.stat(resource);
264
+ let trie;
265
+ return this.toFileStat(provider, resource, stat, undefined, !!resolveMetadata, (stat, siblings) => {
266
+ // lazy trie to check for recursive resolving
267
+ if (!trie) {
268
+ trie = ternary_search_tree_1.TernarySearchTree.forUris(!!(provider.capabilities & 1024 /* PathCaseSensitive */));
269
+ trie.set(resource, true);
270
+ if (Array.isArray(resolveTo) && resolveTo.length) {
271
+ resolveTo.forEach(uri => trie.set(uri, true));
272
+ }
273
+ }
274
+ // check for recursive resolving
275
+ if (Boolean(trie.findSuperstr(stat.resource) || trie.get(stat.resource))) {
276
+ return true;
277
+ }
278
+ // check for resolving single child folders
279
+ if (stat.isDirectory && resolveSingleChildDescendants) {
280
+ return siblings === 1;
281
+ }
282
+ return false;
283
+ });
284
+ }
285
+ async toFileStat(provider, resource, stat, siblings, resolveMetadata, recurse) {
286
+ const fileStat = files_1.FileStat.fromStat(resource, stat);
287
+ // check to recurse for directories
288
+ if (fileStat.isDirectory && recurse(fileStat, siblings)) {
289
+ try {
290
+ const entries = await provider.readdir(resource);
291
+ const resolvedEntries = await Promise.all(entries.map(async ([name, type]) => {
292
+ try {
293
+ const childResource = resource.resolve(name);
294
+ const childStat = resolveMetadata ? await provider.stat(childResource) : { type };
295
+ return await this.toFileStat(provider, childResource, childStat, entries.length, resolveMetadata, recurse);
296
+ }
297
+ catch (error) {
298
+ console.trace(error);
299
+ return null; // can happen e.g. due to permission errors
300
+ }
301
+ }));
302
+ // make sure to get rid of null values that signal a failure to resolve a particular entry
303
+ fileStat.children = resolvedEntries.filter(e => !!e);
304
+ }
305
+ catch (error) {
306
+ console.trace(error);
307
+ fileStat.children = []; // gracefully handle errors, we may not have permissions to read
308
+ }
309
+ return fileStat;
310
+ }
311
+ return fileStat;
312
+ }
313
+ async resolveAll(toResolve) {
314
+ return Promise.all(toResolve.map(async (entry) => {
315
+ try {
316
+ return { stat: await this.doResolveFile(entry.resource, entry.options), success: true };
317
+ }
318
+ catch (error) {
319
+ console.trace(error);
320
+ return { stat: undefined, success: false };
321
+ }
322
+ }));
323
+ }
324
+ /**
325
+ * Tests if the given resource exists in the filesystem.
326
+ * @param resource `URI` of the resource which should be tested.
327
+ * @throws Will throw an error if no {@link FileSystemProvider} is registered for the given resource.
328
+ *
329
+ * @returns A promise that resolves to `true` if the resource exists.
330
+ */
331
+ async exists(resource) {
332
+ const provider = await this.withProvider(resource);
333
+ try {
334
+ const stat = await provider.stat(resource);
335
+ return !!stat;
336
+ }
337
+ catch (error) {
338
+ return false;
339
+ }
340
+ }
341
+ /**
342
+ * Tests a user's permissions for the given resource.
343
+ * @param resource `URI` of the resource which should be tested.
344
+ * @param mode An optional integer that specifies the accessibility checks to be performed.
345
+ * Check `FileAccess.Constants` for possible values of mode.
346
+ * It is possible to create a mask consisting of the bitwise `OR` of two or more values (e.g. FileAccess.Constants.W_OK | FileAccess.Constants.R_OK).
347
+ * If `mode` is not defined, `FileAccess.Constants.F_OK` will be used instead.
348
+ */
349
+ async access(resource, mode) {
350
+ const provider = await this.withProvider(resource);
351
+ if (!(0, files_1.hasAccessCapability)(provider)) {
352
+ return false;
353
+ }
354
+ try {
355
+ await provider.access(resource, mode);
356
+ return true;
357
+ }
358
+ catch (error) {
359
+ return false;
360
+ }
361
+ }
362
+ /**
363
+ * Resolves the fs path of the given URI.
364
+ *
365
+ * USE WITH CAUTION: You should always prefer URIs to paths if possible, as they are
366
+ * portable and platform independent. Paths should only be used in cases you directly
367
+ * interact with the OS, e.g. when running a command on the shell.
368
+ *
369
+ * If you need to display human readable simple or long names then use `LabelProvider` instead.
370
+ * @param resource `URI` of the resource that should be resolved.
371
+ * @throws Will throw an error if no {@link FileSystemProvider} is registered for the given resource.
372
+ *
373
+ * @returns A promise of the resolved fs path.
374
+ */
375
+ async fsPath(resource) {
376
+ const provider = await this.withProvider(resource);
377
+ if (!(0, files_1.hasAccessCapability)(provider)) {
378
+ return resource.path.toString();
379
+ }
380
+ return provider.fsPath(resource);
381
+ }
382
+ // #region Text File Reading/Writing
383
+ async create(resource, value, options) {
384
+ if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
385
+ return this.doCreate(resource, value, options);
386
+ }
387
+ await this.runFileOperationParticipants(resource, undefined, 0 /* CREATE */);
388
+ const event = { correlationId: this.correlationIds++, operation: 0 /* CREATE */, target: resource };
389
+ await this.onWillRunUserOperationEmitter.fire(event);
390
+ let stat;
391
+ try {
392
+ stat = await this.doCreate(resource, value, options);
393
+ }
394
+ catch (error) {
395
+ await this.onDidFailUserOperationEmitter.fire(event);
396
+ throw error;
397
+ }
398
+ await this.onDidRunUserOperationEmitter.fire(event);
399
+ return stat;
400
+ }
401
+ async doCreate(resource, value, options) {
402
+ const encoding = await this.getWriteEncoding(resource, options);
403
+ const encoded = await this.encodingService.encodeStream(value, encoding);
404
+ return this.createFile(resource, encoded, options);
405
+ }
406
+ async write(resource, value, options) {
407
+ const encoding = await this.getWriteEncoding(resource, options);
408
+ const encoded = await this.encodingService.encodeStream(value, encoding);
409
+ return Object.assign(await this.writeFile(resource, encoded, options), { encoding: encoding.encoding });
410
+ }
411
+ async read(resource, options) {
412
+ const [bufferStream, decoder] = await this.doRead(resource, {
413
+ ...options,
414
+ preferUnbuffered: this.shouldReadUnbuffered(options)
415
+ });
416
+ return {
417
+ ...bufferStream,
418
+ encoding: decoder.detected.encoding || encodings_1.UTF8,
419
+ value: await (0, stream_1.consumeStream)(decoder.stream, strings => strings.join(''))
420
+ };
421
+ }
422
+ async readStream(resource, options) {
423
+ const [bufferStream, decoder] = await this.doRead(resource, options);
424
+ return {
425
+ ...bufferStream,
426
+ encoding: decoder.detected.encoding || encodings_1.UTF8,
427
+ value: decoder.stream
428
+ };
429
+ }
430
+ async doRead(resource, options) {
431
+ options = this.resolveReadOptions(options);
432
+ // read stream raw (either buffered or unbuffered)
433
+ let bufferStream;
434
+ if (options === null || options === void 0 ? void 0 : options.preferUnbuffered) {
435
+ const content = await this.readFile(resource, options);
436
+ bufferStream = {
437
+ ...content,
438
+ value: buffer_1.BinaryBufferReadableStream.fromBuffer(content.value)
439
+ };
440
+ }
441
+ else {
442
+ bufferStream = await this.readFileStream(resource, options);
443
+ }
444
+ const decoder = await this.encodingService.decodeStream(bufferStream.value, {
445
+ guessEncoding: options.autoGuessEncoding,
446
+ overwriteEncoding: detectedEncoding => this.getReadEncoding(resource, options, detectedEncoding)
447
+ });
448
+ // validate binary
449
+ if ((options === null || options === void 0 ? void 0 : options.acceptTextOnly) && decoder.detected.seemsBinary) {
450
+ throw new TextFileOperationError(core_1.nls.localizeByDefault('File seems to be binary and cannot be opened as text'), 0 /* FILE_IS_BINARY */, options);
451
+ }
452
+ return [bufferStream, decoder];
453
+ }
454
+ resolveReadOptions(options) {
455
+ options = {
456
+ ...options,
457
+ autoGuessEncoding: typeof (options === null || options === void 0 ? void 0 : options.autoGuessEncoding) === 'boolean' ? options.autoGuessEncoding : this.preferences['files.autoGuessEncoding']
458
+ };
459
+ const limits = options.limits = options.limits || {};
460
+ if (typeof limits.size !== 'number') {
461
+ limits.size = this.preferences['files.maxFileSizeMB'] * 1024 * 1024;
462
+ }
463
+ return options;
464
+ }
465
+ async update(resource, changes, options) {
466
+ const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource);
467
+ try {
468
+ await this.validateWriteFile(provider, resource, options);
469
+ if ((0, files_1.hasUpdateCapability)(provider)) {
470
+ const encoding = await this.getEncodingForResource(resource, options ? options.encoding : undefined);
471
+ ;
472
+ const stat = await provider.updateFile(resource, changes, {
473
+ readEncoding: options.readEncoding,
474
+ writeEncoding: encoding,
475
+ overwriteEncoding: options.overwriteEncoding || false
476
+ });
477
+ return Object.assign(files_1.FileStat.fromStat(resource, stat), { encoding: stat.encoding });
478
+ }
479
+ else {
480
+ throw new Error('incremental file update is not supported');
481
+ }
482
+ }
483
+ catch (error) {
484
+ this.rethrowAsFileOperationError("Unable to write file '{0}' ({1})", resource, error, options);
485
+ }
486
+ }
487
+ // #endregion
488
+ // #region File Reading/Writing
489
+ async createFile(resource, bufferOrReadableOrStream = buffer_1.BinaryBuffer.fromString(''), options) {
490
+ // validate overwrite
491
+ if (!(options === null || options === void 0 ? void 0 : options.overwrite) && await this.exists(resource)) {
492
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to create file '{0}' that already exists when overwrite flag is not set", this.resourceForError(resource)), 3 /* FILE_MODIFIED_SINCE */, options);
493
+ }
494
+ // do write into file (this will create it too)
495
+ const fileStat = await this.writeFile(resource, bufferOrReadableOrStream);
496
+ // events
497
+ this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(resource, 0 /* CREATE */, fileStat));
498
+ return fileStat;
499
+ }
500
+ async writeFile(resource, bufferOrReadableOrStream, options) {
501
+ const provider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(resource), resource);
502
+ try {
503
+ // validate write
504
+ const stat = await this.validateWriteFile(provider, resource, options);
505
+ // mkdir recursively as needed
506
+ if (!stat) {
507
+ await this.mkdirp(provider, resource.parent);
508
+ }
509
+ // optimization: if the provider has unbuffered write capability and the data
510
+ // to write is a Readable, we consume up to 3 chunks and try to write the data
511
+ // unbuffered to reduce the overhead. If the Readable has more data to provide
512
+ // we continue to write buffered.
513
+ let bufferOrReadableOrStreamOrBufferedStream;
514
+ if ((0, files_1.hasReadWriteCapability)(provider) && !(bufferOrReadableOrStream instanceof buffer_1.BinaryBuffer)) {
515
+ if ((0, stream_1.isReadableStream)(bufferOrReadableOrStream)) {
516
+ const bufferedStream = await (0, stream_1.peekStream)(bufferOrReadableOrStream, 3);
517
+ if (bufferedStream.ended) {
518
+ bufferOrReadableOrStreamOrBufferedStream = buffer_1.BinaryBuffer.concat(bufferedStream.buffer);
519
+ }
520
+ else {
521
+ bufferOrReadableOrStreamOrBufferedStream = bufferedStream;
522
+ }
523
+ }
524
+ else {
525
+ bufferOrReadableOrStreamOrBufferedStream = (0, stream_1.peekReadable)(bufferOrReadableOrStream, data => buffer_1.BinaryBuffer.concat(data), 3);
526
+ }
527
+ }
528
+ else {
529
+ bufferOrReadableOrStreamOrBufferedStream = bufferOrReadableOrStream;
530
+ }
531
+ // write file: unbuffered (only if data to write is a buffer, or the provider has no buffered write capability)
532
+ if (!(0, files_1.hasOpenReadWriteCloseCapability)(provider) || ((0, files_1.hasReadWriteCapability)(provider) && bufferOrReadableOrStreamOrBufferedStream instanceof buffer_1.BinaryBuffer)) {
533
+ await this.doWriteUnbuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream);
534
+ }
535
+ // write file: buffered
536
+ else {
537
+ await this.doWriteBuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream instanceof buffer_1.BinaryBuffer ? buffer_1.BinaryBufferReadable.fromBuffer(bufferOrReadableOrStreamOrBufferedStream) : bufferOrReadableOrStreamOrBufferedStream);
538
+ }
539
+ }
540
+ catch (error) {
541
+ this.rethrowAsFileOperationError("Unable to write file '{0}' ({1})", resource, error, options);
542
+ }
543
+ return this.resolve(resource, { resolveMetadata: true });
544
+ }
545
+ async validateWriteFile(provider, resource, options) {
546
+ let stat = undefined;
547
+ try {
548
+ stat = await provider.stat(resource);
549
+ }
550
+ catch (error) {
551
+ return undefined; // file might not exist
552
+ }
553
+ // file cannot be directory
554
+ if ((stat.type & files_1.FileType.Directory) !== 0) {
555
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to write file '{0}' that is actually a directory", this.resourceForError(resource)), 0 /* FILE_IS_DIRECTORY */, options);
556
+ }
557
+ if (this.modifiedSince(stat, options)) {
558
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault('File Modified Since'), 3 /* FILE_MODIFIED_SINCE */, options);
559
+ }
560
+ return stat;
561
+ }
562
+ /**
563
+ * Dirty write prevention: if the file on disk has been changed and does not match our expected
564
+ * mtime and etag, we bail out to prevent dirty writing.
565
+ *
566
+ * First, we check for a mtime that is in the future before we do more checks. The assumption is
567
+ * that only the mtime is an indicator for a file that has changed on disk.
568
+ *
569
+ * Second, if the mtime has advanced, we compare the size of the file on disk with our previous
570
+ * one using the etag() function. Relying only on the mtime check has proven to produce false
571
+ * positives due to file system weirdness (especially around remote file systems). As such, the
572
+ * check for size is a weaker check because it can return a false negative if the file has changed
573
+ * but to the same length. This is a compromise we take to avoid having to produce checksums of
574
+ * the file content for comparison which would be much slower to compute.
575
+ */
576
+ modifiedSince(stat, options) {
577
+ return !!options && typeof options.mtime === 'number' && typeof options.etag === 'string' && options.etag !== files_1.ETAG_DISABLED &&
578
+ typeof stat.mtime === 'number' && typeof stat.size === 'number' &&
579
+ options.mtime < stat.mtime && options.etag !== (0, files_1.etag)({ mtime: options.mtime /* not using stat.mtime for a reason, see above */, size: stat.size });
580
+ }
581
+ shouldReadUnbuffered(options) {
582
+ // optimization: since we know that the caller does not
583
+ // care about buffering, we indicate this to the reader.
584
+ // this reduces all the overhead the buffered reading
585
+ // has (open, read, close) if the provider supports
586
+ // unbuffered reading.
587
+ //
588
+ // However, if we read only part of the file we still
589
+ // want buffered reading as otherwise we need to read
590
+ // the whole file and cut out the specified part later.
591
+ return (options === null || options === void 0 ? void 0 : options.position) === undefined && (options === null || options === void 0 ? void 0 : options.length) === undefined;
592
+ }
593
+ async readFile(resource, options) {
594
+ const provider = await this.withReadProvider(resource);
595
+ const stream = await this.doReadAsFileStream(provider, resource, {
596
+ ...options,
597
+ preferUnbuffered: this.shouldReadUnbuffered(options)
598
+ });
599
+ return {
600
+ ...stream,
601
+ value: await buffer_1.BinaryBufferReadableStream.toBuffer(stream.value)
602
+ };
603
+ }
604
+ async readFileStream(resource, options) {
605
+ const provider = await this.withReadProvider(resource);
606
+ return this.doReadAsFileStream(provider, resource, options);
607
+ }
608
+ async doReadAsFileStream(provider, resource, options) {
609
+ // install a cancellation token that gets cancelled
610
+ // when any error occurs. this allows us to resolve
611
+ // the content of the file while resolving metadata
612
+ // but still cancel the operation in certain cases.
613
+ const cancellableSource = new cancellation_1.CancellationTokenSource();
614
+ // validate read operation
615
+ const statPromise = this.validateReadFile(resource, options).then(stat => stat, error => {
616
+ cancellableSource.cancel();
617
+ throw error;
618
+ });
619
+ try {
620
+ // if the etag is provided, we await the result of the validation
621
+ // due to the likelyhood of hitting a NOT_MODIFIED_SINCE result.
622
+ // otherwise, we let it run in parallel to the file reading for
623
+ // optimal startup performance.
624
+ if (options && typeof options.etag === 'string' && options.etag !== files_1.ETAG_DISABLED) {
625
+ await statPromise;
626
+ }
627
+ let fileStreamPromise;
628
+ // read unbuffered (only if either preferred, or the provider has no buffered read capability)
629
+ if (!((0, files_1.hasOpenReadWriteCloseCapability)(provider) || (0, files_1.hasFileReadStreamCapability)(provider)) || ((0, files_1.hasReadWriteCapability)(provider) && (options === null || options === void 0 ? void 0 : options.preferUnbuffered))) {
630
+ fileStreamPromise = this.readFileUnbuffered(provider, resource, options);
631
+ }
632
+ // read streamed (always prefer over primitive buffered read)
633
+ else if ((0, files_1.hasFileReadStreamCapability)(provider)) {
634
+ fileStreamPromise = Promise.resolve(this.readFileStreamed(provider, resource, cancellableSource.token, options));
635
+ }
636
+ // read buffered
637
+ else {
638
+ fileStreamPromise = Promise.resolve(this.readFileBuffered(provider, resource, cancellableSource.token, options));
639
+ }
640
+ const [fileStat, fileStream] = await Promise.all([statPromise, fileStreamPromise]);
641
+ return {
642
+ ...fileStat,
643
+ value: fileStream
644
+ };
645
+ }
646
+ catch (error) {
647
+ this.rethrowAsFileOperationError("Unable to read file '{0}' ({1})", resource, error, options);
648
+ }
649
+ }
650
+ readFileStreamed(provider, resource, token, options = Object.create(null)) {
651
+ const fileStream = provider.readFileStream(resource, options, token);
652
+ return (0, stream_1.transform)(fileStream, {
653
+ data: data => data instanceof buffer_1.BinaryBuffer ? data : buffer_1.BinaryBuffer.wrap(data),
654
+ error: error => this.asFileOperationError("Unable to read file '{0}' ({1})", resource, error, options)
655
+ }, data => buffer_1.BinaryBuffer.concat(data));
656
+ }
657
+ readFileBuffered(provider, resource, token, options = Object.create(null)) {
658
+ const stream = buffer_1.BinaryBufferWriteableStream.create();
659
+ (0, io_1.readFileIntoStream)(provider, resource, stream, data => data, {
660
+ ...options,
661
+ bufferSize: this.BUFFER_SIZE,
662
+ errorTransformer: error => this.asFileOperationError("Unable to read file '{0}' ({1})", resource, error, options)
663
+ }, token);
664
+ return stream;
665
+ }
666
+ rethrowAsFileOperationError(message, resource, error, options) {
667
+ throw this.asFileOperationError(message, resource, error, options);
668
+ }
669
+ asFileOperationError(message, resource, error, options) {
670
+ const fileOperationError = new files_1.FileOperationError(core_1.nls.localizeByDefault(message, this.resourceForError(resource), (0, files_1.ensureFileSystemProviderError)(error).toString()), (0, files_1.toFileOperationResult)(error), options);
671
+ fileOperationError.stack = `${fileOperationError.stack}\nCaused by: ${error.stack}`;
672
+ return fileOperationError;
673
+ }
674
+ async readFileUnbuffered(provider, resource, options) {
675
+ let buffer = await provider.readFile(resource);
676
+ // respect position option
677
+ if (options && typeof options.position === 'number') {
678
+ buffer = buffer.slice(options.position);
679
+ }
680
+ // respect length option
681
+ if (options && typeof options.length === 'number') {
682
+ buffer = buffer.slice(0, options.length);
683
+ }
684
+ // Throw if file is too large to load
685
+ this.validateReadFileLimits(resource, buffer.byteLength, options);
686
+ return buffer_1.BinaryBufferReadableStream.fromBuffer(buffer_1.BinaryBuffer.wrap(buffer));
687
+ }
688
+ async validateReadFile(resource, options) {
689
+ const stat = await this.resolve(resource, { resolveMetadata: true });
690
+ // Throw if resource is a directory
691
+ if (stat.isDirectory) {
692
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to read file '{0}' that is actually a directory", this.resourceForError(resource)), 0 /* FILE_IS_DIRECTORY */, options);
693
+ }
694
+ // Throw if file not modified since (unless disabled)
695
+ if (options && typeof options.etag === 'string' && options.etag !== files_1.ETAG_DISABLED && options.etag === stat.etag) {
696
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault('File not modified since'), 2 /* FILE_NOT_MODIFIED_SINCE */, options);
697
+ }
698
+ // Throw if file is too large to load
699
+ this.validateReadFileLimits(resource, stat.size, options);
700
+ return stat;
701
+ }
702
+ validateReadFileLimits(resource, size, options) {
703
+ if (options === null || options === void 0 ? void 0 : options.limits) {
704
+ let tooLargeErrorResult = undefined;
705
+ if (typeof options.limits.memory === 'number' && size > options.limits.memory) {
706
+ tooLargeErrorResult = 9 /* FILE_EXCEEDS_MEMORY_LIMIT */;
707
+ }
708
+ if (typeof options.limits.size === 'number' && size > options.limits.size) {
709
+ tooLargeErrorResult = 7 /* FILE_TOO_LARGE */;
710
+ }
711
+ if (typeof tooLargeErrorResult === 'number') {
712
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to read file '{0}' that is too large to open", this.resourceForError(resource)), tooLargeErrorResult);
713
+ }
714
+ }
715
+ }
716
+ // #endregion
717
+ // #region Move/Copy/Delete/Create Folder
718
+ async move(source, target, options) {
719
+ if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
720
+ return this.doMove(source, target, options.overwrite);
721
+ }
722
+ await this.runFileOperationParticipants(target, source, 2 /* MOVE */);
723
+ const event = { correlationId: this.correlationIds++, operation: 2 /* MOVE */, target, source };
724
+ await this.onWillRunUserOperationEmitter.fire(event);
725
+ let stat;
726
+ try {
727
+ stat = await this.doMove(source, target, options === null || options === void 0 ? void 0 : options.overwrite);
728
+ }
729
+ catch (error) {
730
+ await this.onDidFailUserOperationEmitter.fire(event);
731
+ throw error;
732
+ }
733
+ await this.onDidRunUserOperationEmitter.fire(event);
734
+ return stat;
735
+ }
736
+ async doMove(source, target, overwrite) {
737
+ const sourceProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(source), source);
738
+ const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
739
+ // move
740
+ const mode = await this.doMoveCopy(sourceProvider, source, targetProvider, target, 'move', !!overwrite);
741
+ // resolve and send events
742
+ const fileStat = await this.resolve(target, { resolveMetadata: true });
743
+ this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(source, mode === 'move' ? 2 /* MOVE */ : 3 /* COPY */, fileStat));
744
+ return fileStat;
745
+ }
746
+ async copy(source, target, options) {
747
+ if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
748
+ return this.doCopy(source, target, options.overwrite);
749
+ }
750
+ await this.runFileOperationParticipants(target, source, 3 /* COPY */);
751
+ const event = { correlationId: this.correlationIds++, operation: 3 /* COPY */, target, source };
752
+ await this.onWillRunUserOperationEmitter.fire(event);
753
+ let stat;
754
+ try {
755
+ stat = await this.doCopy(source, target, options === null || options === void 0 ? void 0 : options.overwrite);
756
+ }
757
+ catch (error) {
758
+ await this.onDidFailUserOperationEmitter.fire(event);
759
+ throw error;
760
+ }
761
+ await this.onDidRunUserOperationEmitter.fire(event);
762
+ return stat;
763
+ }
764
+ async doCopy(source, target, overwrite) {
765
+ const sourceProvider = await this.withReadProvider(source);
766
+ const targetProvider = this.throwIfFileSystemIsReadonly(await this.withWriteProvider(target), target);
767
+ // copy
768
+ const mode = await this.doMoveCopy(sourceProvider, source, targetProvider, target, 'copy', !!overwrite);
769
+ // resolve and send events
770
+ const fileStat = await this.resolve(target, { resolveMetadata: true });
771
+ this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(source, mode === 'copy' ? 3 /* COPY */ : 2 /* MOVE */, fileStat));
772
+ return fileStat;
773
+ }
774
+ async doMoveCopy(sourceProvider, source, targetProvider, target, mode, overwrite) {
775
+ if (source.toString() === target.toString()) {
776
+ return mode; // simulate node.js behaviour here and do a no-op if paths match
777
+ }
778
+ // validation
779
+ const { exists, isSameResourceWithDifferentPathCase } = await this.doValidateMoveCopy(sourceProvider, source, targetProvider, target, mode, overwrite);
780
+ // if target exists get valid target
781
+ if (exists && !overwrite) {
782
+ const parent = await this.resolve(target.parent);
783
+ const targetFileStat = await this.resolve(target);
784
+ target = filesystem_utils_1.FileSystemUtils.generateUniqueResourceURI(parent, target, targetFileStat.isDirectory, isSameResourceWithDifferentPathCase ? 'copy' : undefined);
785
+ }
786
+ // delete as needed (unless target is same resource with different path case)
787
+ if (exists && !isSameResourceWithDifferentPathCase && overwrite) {
788
+ await this.delete(target, { recursive: true });
789
+ }
790
+ // create parent folders
791
+ await this.mkdirp(targetProvider, target.parent);
792
+ // copy source => target
793
+ if (mode === 'copy') {
794
+ // same provider with fast copy: leverage copy() functionality
795
+ if (sourceProvider === targetProvider && (0, files_1.hasFileFolderCopyCapability)(sourceProvider)) {
796
+ await sourceProvider.copy(source, target, { overwrite });
797
+ }
798
+ // when copying via buffer/unbuffered, we have to manually
799
+ // traverse the source if it is a folder and not a file
800
+ else {
801
+ const sourceFile = await this.resolve(source);
802
+ if (sourceFile.isDirectory) {
803
+ await this.doCopyFolder(sourceProvider, sourceFile, targetProvider, target);
804
+ }
805
+ else {
806
+ await this.doCopyFile(sourceProvider, source, targetProvider, target);
807
+ }
808
+ }
809
+ return mode;
810
+ }
811
+ // move source => target
812
+ else {
813
+ // same provider: leverage rename() functionality
814
+ if (sourceProvider === targetProvider) {
815
+ await sourceProvider.rename(source, target, { overwrite });
816
+ return mode;
817
+ }
818
+ // across providers: copy to target & delete at source
819
+ else {
820
+ await this.doMoveCopy(sourceProvider, source, targetProvider, target, 'copy', overwrite);
821
+ await this.delete(source, { recursive: true });
822
+ return 'copy';
823
+ }
824
+ }
825
+ }
826
+ async doCopyFile(sourceProvider, source, targetProvider, target) {
827
+ // copy: source (buffered) => target (buffered)
828
+ if ((0, files_1.hasOpenReadWriteCloseCapability)(sourceProvider) && (0, files_1.hasOpenReadWriteCloseCapability)(targetProvider)) {
829
+ return this.doPipeBuffered(sourceProvider, source, targetProvider, target);
830
+ }
831
+ // copy: source (buffered) => target (unbuffered)
832
+ if ((0, files_1.hasOpenReadWriteCloseCapability)(sourceProvider) && (0, files_1.hasReadWriteCapability)(targetProvider)) {
833
+ return this.doPipeBufferedToUnbuffered(sourceProvider, source, targetProvider, target);
834
+ }
835
+ // copy: source (unbuffered) => target (buffered)
836
+ if ((0, files_1.hasReadWriteCapability)(sourceProvider) && (0, files_1.hasOpenReadWriteCloseCapability)(targetProvider)) {
837
+ return this.doPipeUnbufferedToBuffered(sourceProvider, source, targetProvider, target);
838
+ }
839
+ // copy: source (unbuffered) => target (unbuffered)
840
+ if ((0, files_1.hasReadWriteCapability)(sourceProvider) && (0, files_1.hasReadWriteCapability)(targetProvider)) {
841
+ return this.doPipeUnbuffered(sourceProvider, source, targetProvider, target);
842
+ }
843
+ }
844
+ async doCopyFolder(sourceProvider, sourceFolder, targetProvider, targetFolder) {
845
+ // create folder in target
846
+ await targetProvider.mkdir(targetFolder);
847
+ // create children in target
848
+ if (Array.isArray(sourceFolder.children)) {
849
+ await Promise.all(sourceFolder.children.map(async (sourceChild) => {
850
+ const targetChild = targetFolder.resolve(sourceChild.name);
851
+ if (sourceChild.isDirectory) {
852
+ return this.doCopyFolder(sourceProvider, await this.resolve(sourceChild.resource), targetProvider, targetChild);
853
+ }
854
+ else {
855
+ return this.doCopyFile(sourceProvider, sourceChild.resource, targetProvider, targetChild);
856
+ }
857
+ }));
858
+ }
859
+ }
860
+ async doValidateMoveCopy(sourceProvider, source, targetProvider, target, mode, overwrite) {
861
+ let isSameResourceWithDifferentPathCase = false;
862
+ // Check if source is equal or parent to target (requires providers to be the same)
863
+ if (sourceProvider === targetProvider) {
864
+ const isPathCaseSensitive = !!(sourceProvider.capabilities & 1024 /* PathCaseSensitive */);
865
+ if (!isPathCaseSensitive) {
866
+ isSameResourceWithDifferentPathCase = source.toString().toLowerCase() === target.toString().toLowerCase();
867
+ }
868
+ if (isSameResourceWithDifferentPathCase && mode === 'copy') {
869
+ throw new Error(core_1.nls.localizeByDefault("Unable to move/copy when source '{0}' is parent of target '{1}'.", this.resourceForError(source), this.resourceForError(target)));
870
+ }
871
+ if (!isSameResourceWithDifferentPathCase && target.isEqualOrParent(source, isPathCaseSensitive)) {
872
+ throw new Error(core_1.nls.localizeByDefault("Unable to move/copy when source '{0}' is parent of target '{1}'.", this.resourceForError(source), this.resourceForError(target)));
873
+ }
874
+ }
875
+ // Extra checks if target exists and this is not a rename
876
+ const exists = await this.exists(target);
877
+ if (exists && !isSameResourceWithDifferentPathCase) {
878
+ // Special case: if the target is a parent of the source, we cannot delete
879
+ // it as it would delete the source as well. In this case we have to throw
880
+ if (sourceProvider === targetProvider) {
881
+ const isPathCaseSensitive = !!(sourceProvider.capabilities & 1024 /* PathCaseSensitive */);
882
+ if (source.isEqualOrParent(target, isPathCaseSensitive)) {
883
+ throw new Error(core_1.nls.localizeByDefault("Unable to move/copy '{0}' into '{1}' since a file would replace the folder it is contained in.", this.resourceForError(source), this.resourceForError(target)));
884
+ }
885
+ }
886
+ }
887
+ return { exists, isSameResourceWithDifferentPathCase };
888
+ }
889
+ async createFolder(resource, options = {}) {
890
+ const { fromUserGesture = true, } = options;
891
+ const provider = this.throwIfFileSystemIsReadonly(await this.withProvider(resource), resource);
892
+ // mkdir recursively
893
+ await this.mkdirp(provider, resource);
894
+ // events
895
+ const fileStat = await this.resolve(resource, { resolveMetadata: true });
896
+ if (fromUserGesture) {
897
+ this.onDidRunUserOperationEmitter.fire({ correlationId: this.correlationIds++, operation: 0 /* CREATE */, target: resource });
898
+ }
899
+ else {
900
+ this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(resource, 0 /* CREATE */, fileStat));
901
+ }
902
+ return fileStat;
903
+ }
904
+ async mkdirp(provider, directory) {
905
+ const directoriesToCreate = [];
906
+ // mkdir until we reach root
907
+ while (!directory.path.isRoot) {
908
+ try {
909
+ const stat = await provider.stat(directory);
910
+ if ((stat.type & files_1.FileType.Directory) === 0) {
911
+ throw new Error(core_1.nls.localizeByDefault("Unable to create folder '{0}' that already exists but is not a directory", this.resourceForError(directory)));
912
+ }
913
+ break; // we have hit a directory that exists -> good
914
+ }
915
+ catch (error) {
916
+ // Bubble up any other error that is not file not found
917
+ if ((0, files_1.toFileSystemProviderErrorCode)(error) !== files_1.FileSystemProviderErrorCode.FileNotFound) {
918
+ throw error;
919
+ }
920
+ // Upon error, remember directories that need to be created
921
+ directoriesToCreate.push(directory.path.base);
922
+ // Continue up
923
+ directory = directory.parent;
924
+ }
925
+ }
926
+ // Create directories as needed
927
+ for (let i = directoriesToCreate.length - 1; i >= 0; i--) {
928
+ directory = directory.resolve(directoriesToCreate[i]);
929
+ try {
930
+ await provider.mkdir(directory);
931
+ }
932
+ catch (error) {
933
+ if ((0, files_1.toFileSystemProviderErrorCode)(error) !== files_1.FileSystemProviderErrorCode.FileExists) {
934
+ // For mkdirp() we tolerate that the mkdir() call fails
935
+ // in case the folder already exists. This follows node.js
936
+ // own implementation of fs.mkdir({ recursive: true }) and
937
+ // reduces the chances of race conditions leading to errors
938
+ // if multiple calls try to create the same folders
939
+ // As such, we only throw an error here if it is other than
940
+ // the fact that the file already exists.
941
+ // (see also https://github.com/microsoft/vscode/issues/89834)
942
+ throw error;
943
+ }
944
+ }
945
+ }
946
+ }
947
+ async delete(resource, options) {
948
+ if ((options === null || options === void 0 ? void 0 : options.fromUserGesture) === false) {
949
+ return this.doDelete(resource, options);
950
+ }
951
+ await this.runFileOperationParticipants(resource, undefined, 1 /* DELETE */);
952
+ const event = { correlationId: this.correlationIds++, operation: 1 /* DELETE */, target: resource };
953
+ await this.onWillRunUserOperationEmitter.fire(event);
954
+ try {
955
+ await this.doDelete(resource, options);
956
+ }
957
+ catch (error) {
958
+ await this.onDidFailUserOperationEmitter.fire(event);
959
+ throw error;
960
+ }
961
+ await this.onDidRunUserOperationEmitter.fire(event);
962
+ }
963
+ async doDelete(resource, options) {
964
+ const provider = this.throwIfFileSystemIsReadonly(await this.withProvider(resource), resource);
965
+ // Validate trash support
966
+ const useTrash = !!(options === null || options === void 0 ? void 0 : options.useTrash);
967
+ if (useTrash && !(provider.capabilities & 4096 /* Trash */)) {
968
+ throw new Error(core_1.nls.localizeByDefault("Unable to delete file '{0}' via trash because provider does not support it.", this.resourceForError(resource)));
969
+ }
970
+ // Validate delete
971
+ const exists = await this.exists(resource);
972
+ if (!exists) {
973
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to delete nonexistent file '{0}'", this.resourceForError(resource)), 1 /* FILE_NOT_FOUND */);
974
+ }
975
+ // Validate recursive
976
+ const recursive = !!(options === null || options === void 0 ? void 0 : options.recursive);
977
+ if (!recursive && exists) {
978
+ const stat = await this.resolve(resource);
979
+ if (stat.isDirectory && Array.isArray(stat.children) && stat.children.length > 0) {
980
+ throw new Error(core_1.nls.localizeByDefault("Unable to delete non-empty folder '{0}'.", this.resourceForError(resource)));
981
+ }
982
+ }
983
+ // Delete through provider
984
+ await provider.delete(resource, { recursive, useTrash });
985
+ // Events
986
+ this.onDidRunOperationEmitter.fire(new files_1.FileOperationEvent(resource, 1 /* DELETE */));
987
+ }
988
+ /**
989
+ * An event that is emitted when files are changed on the disk.
990
+ */
991
+ get onDidFilesChange() {
992
+ return this.onDidFilesChangeEmitter.event;
993
+ }
994
+ watch(resource, options = { recursive: false, excludes: [] }) {
995
+ const resolvedOptions = {
996
+ ...options,
997
+ // always ignore temporary upload files
998
+ excludes: options.excludes.concat('**/theia_upload_*')
999
+ };
1000
+ let watchDisposed = false;
1001
+ let watchDisposable = disposable_1.Disposable.create(() => watchDisposed = true);
1002
+ // Watch and wire in disposable which is async but
1003
+ // check if we got disposed meanwhile and forward
1004
+ this.doWatch(resource, resolvedOptions).then(disposable => {
1005
+ if (watchDisposed) {
1006
+ disposable.dispose();
1007
+ }
1008
+ else {
1009
+ watchDisposable = disposable;
1010
+ }
1011
+ }, error => console.error(error));
1012
+ return disposable_1.Disposable.create(() => watchDisposable.dispose());
1013
+ }
1014
+ async doWatch(resource, options) {
1015
+ const provider = await this.withProvider(resource);
1016
+ const key = this.toWatchKey(provider, resource, options);
1017
+ // Only start watching if we are the first for the given key
1018
+ const watcher = this.activeWatchers.get(key) || { count: 0, disposable: provider.watch(resource, options) };
1019
+ if (!this.activeWatchers.has(key)) {
1020
+ this.activeWatchers.set(key, watcher);
1021
+ }
1022
+ // Increment usage counter
1023
+ watcher.count += 1;
1024
+ return disposable_1.Disposable.create(() => {
1025
+ // Unref
1026
+ watcher.count--;
1027
+ // Dispose only when last user is reached
1028
+ if (watcher.count === 0) {
1029
+ watcher.disposable.dispose();
1030
+ this.activeWatchers.delete(key);
1031
+ }
1032
+ });
1033
+ }
1034
+ toWatchKey(provider, resource, options) {
1035
+ return [
1036
+ this.toMapKey(provider, resource),
1037
+ String(options.recursive),
1038
+ options.excludes.join() // use excludes as part of the key
1039
+ ].join();
1040
+ }
1041
+ ensureWriteQueue(provider, resource, task) {
1042
+ // ensure to never write to the same resource without finishing
1043
+ // the one write. this ensures a write finishes consistently
1044
+ // (even with error) before another write is done.
1045
+ const queueKey = this.toMapKey(provider, resource);
1046
+ const writeQueue = (this.writeQueues.get(queueKey) || Promise.resolve()).then(task, task);
1047
+ this.writeQueues.set(queueKey, writeQueue);
1048
+ return writeQueue;
1049
+ }
1050
+ toMapKey(provider, resource) {
1051
+ const isPathCaseSensitive = !!(provider.capabilities & 1024 /* PathCaseSensitive */);
1052
+ return isPathCaseSensitive ? resource.toString() : resource.toString().toLowerCase();
1053
+ }
1054
+ async doWriteBuffered(provider, resource, readableOrStreamOrBufferedStream) {
1055
+ return this.ensureWriteQueue(provider, resource, async () => {
1056
+ // open handle
1057
+ const handle = await provider.open(resource, { create: true });
1058
+ // write into handle until all bytes from buffer have been written
1059
+ try {
1060
+ if ((0, stream_1.isReadableStream)(readableOrStreamOrBufferedStream) || (0, stream_1.isReadableBufferedStream)(readableOrStreamOrBufferedStream)) {
1061
+ await this.doWriteStreamBufferedQueued(provider, handle, readableOrStreamOrBufferedStream);
1062
+ }
1063
+ else {
1064
+ await this.doWriteReadableBufferedQueued(provider, handle, readableOrStreamOrBufferedStream);
1065
+ }
1066
+ }
1067
+ catch (error) {
1068
+ throw (0, files_1.ensureFileSystemProviderError)(error);
1069
+ }
1070
+ finally {
1071
+ // close handle always
1072
+ await provider.close(handle);
1073
+ }
1074
+ });
1075
+ }
1076
+ async doWriteStreamBufferedQueued(provider, handle, streamOrBufferedStream) {
1077
+ let posInFile = 0;
1078
+ let stream;
1079
+ // Buffered stream: consume the buffer first by writing
1080
+ // it to the target before reading from the stream.
1081
+ if ((0, stream_1.isReadableBufferedStream)(streamOrBufferedStream)) {
1082
+ if (streamOrBufferedStream.buffer.length > 0) {
1083
+ const chunk = buffer_1.BinaryBuffer.concat(streamOrBufferedStream.buffer);
1084
+ await this.doWriteBuffer(provider, handle, chunk, chunk.byteLength, posInFile, 0);
1085
+ posInFile += chunk.byteLength;
1086
+ }
1087
+ // If the stream has been consumed, return early
1088
+ if (streamOrBufferedStream.ended) {
1089
+ return;
1090
+ }
1091
+ stream = streamOrBufferedStream.stream;
1092
+ }
1093
+ // Unbuffered stream - just take as is
1094
+ else {
1095
+ stream = streamOrBufferedStream;
1096
+ }
1097
+ return new Promise(async (resolve, reject) => {
1098
+ stream.on('data', async (chunk) => {
1099
+ // pause stream to perform async write operation
1100
+ stream.pause();
1101
+ try {
1102
+ await this.doWriteBuffer(provider, handle, chunk, chunk.byteLength, posInFile, 0);
1103
+ }
1104
+ catch (error) {
1105
+ return reject(error);
1106
+ }
1107
+ posInFile += chunk.byteLength;
1108
+ // resume stream now that we have successfully written
1109
+ // run this on the next tick to prevent increasing the
1110
+ // execution stack because resume() may call the event
1111
+ // handler again before finishing.
1112
+ setTimeout(() => stream.resume());
1113
+ });
1114
+ stream.on('error', error => reject(error));
1115
+ stream.on('end', () => resolve());
1116
+ });
1117
+ }
1118
+ async doWriteReadableBufferedQueued(provider, handle, readable) {
1119
+ let posInFile = 0;
1120
+ let chunk;
1121
+ while ((chunk = readable.read()) !== null) {
1122
+ await this.doWriteBuffer(provider, handle, chunk, chunk.byteLength, posInFile, 0);
1123
+ posInFile += chunk.byteLength;
1124
+ }
1125
+ }
1126
+ async doWriteBuffer(provider, handle, buffer, length, posInFile, posInBuffer) {
1127
+ let totalBytesWritten = 0;
1128
+ while (totalBytesWritten < length) {
1129
+ const bytesWritten = await provider.write(handle, posInFile + totalBytesWritten, buffer.buffer, posInBuffer + totalBytesWritten, length - totalBytesWritten);
1130
+ totalBytesWritten += bytesWritten;
1131
+ }
1132
+ }
1133
+ async doWriteUnbuffered(provider, resource, bufferOrReadableOrStreamOrBufferedStream) {
1134
+ return this.ensureWriteQueue(provider, resource, () => this.doWriteUnbufferedQueued(provider, resource, bufferOrReadableOrStreamOrBufferedStream));
1135
+ }
1136
+ async doWriteUnbufferedQueued(provider, resource, bufferOrReadableOrStreamOrBufferedStream) {
1137
+ let buffer;
1138
+ if (bufferOrReadableOrStreamOrBufferedStream instanceof buffer_1.BinaryBuffer) {
1139
+ buffer = bufferOrReadableOrStreamOrBufferedStream;
1140
+ }
1141
+ else if ((0, stream_1.isReadableStream)(bufferOrReadableOrStreamOrBufferedStream)) {
1142
+ buffer = await buffer_1.BinaryBufferReadableStream.toBuffer(bufferOrReadableOrStreamOrBufferedStream);
1143
+ }
1144
+ else if ((0, stream_1.isReadableBufferedStream)(bufferOrReadableOrStreamOrBufferedStream)) {
1145
+ buffer = await buffer_1.BinaryBufferReadableBufferedStream.toBuffer(bufferOrReadableOrStreamOrBufferedStream);
1146
+ }
1147
+ else {
1148
+ buffer = buffer_1.BinaryBufferReadable.toBuffer(bufferOrReadableOrStreamOrBufferedStream);
1149
+ }
1150
+ return provider.writeFile(resource, buffer.buffer, { create: true, overwrite: true });
1151
+ }
1152
+ async doPipeBuffered(sourceProvider, source, targetProvider, target) {
1153
+ return this.ensureWriteQueue(targetProvider, target, () => this.doPipeBufferedQueued(sourceProvider, source, targetProvider, target));
1154
+ }
1155
+ async doPipeBufferedQueued(sourceProvider, source, targetProvider, target) {
1156
+ let sourceHandle = undefined;
1157
+ let targetHandle = undefined;
1158
+ try {
1159
+ // Open handles
1160
+ sourceHandle = await sourceProvider.open(source, { create: false });
1161
+ targetHandle = await targetProvider.open(target, { create: true });
1162
+ const buffer = buffer_1.BinaryBuffer.alloc(this.BUFFER_SIZE);
1163
+ let posInFile = 0;
1164
+ let posInBuffer = 0;
1165
+ let bytesRead = 0;
1166
+ do {
1167
+ // read from source (sourceHandle) at current position (posInFile) into buffer (buffer) at
1168
+ // buffer position (posInBuffer) up to the size of the buffer (buffer.byteLength).
1169
+ bytesRead = await sourceProvider.read(sourceHandle, posInFile, buffer.buffer, posInBuffer, buffer.byteLength - posInBuffer);
1170
+ // write into target (targetHandle) at current position (posInFile) from buffer (buffer) at
1171
+ // buffer position (posInBuffer) all bytes we read (bytesRead).
1172
+ await this.doWriteBuffer(targetProvider, targetHandle, buffer, bytesRead, posInFile, posInBuffer);
1173
+ posInFile += bytesRead;
1174
+ posInBuffer += bytesRead;
1175
+ // when buffer full, fill it again from the beginning
1176
+ if (posInBuffer === buffer.byteLength) {
1177
+ posInBuffer = 0;
1178
+ }
1179
+ } while (bytesRead > 0);
1180
+ }
1181
+ catch (error) {
1182
+ throw (0, files_1.ensureFileSystemProviderError)(error);
1183
+ }
1184
+ finally {
1185
+ await Promise.all([
1186
+ typeof sourceHandle === 'number' ? sourceProvider.close(sourceHandle) : Promise.resolve(),
1187
+ typeof targetHandle === 'number' ? targetProvider.close(targetHandle) : Promise.resolve(),
1188
+ ]);
1189
+ }
1190
+ }
1191
+ async doPipeUnbuffered(sourceProvider, source, targetProvider, target) {
1192
+ return this.ensureWriteQueue(targetProvider, target, () => this.doPipeUnbufferedQueued(sourceProvider, source, targetProvider, target));
1193
+ }
1194
+ async doPipeUnbufferedQueued(sourceProvider, source, targetProvider, target) {
1195
+ return targetProvider.writeFile(target, await sourceProvider.readFile(source), { create: true, overwrite: true });
1196
+ }
1197
+ async doPipeUnbufferedToBuffered(sourceProvider, source, targetProvider, target) {
1198
+ return this.ensureWriteQueue(targetProvider, target, () => this.doPipeUnbufferedToBufferedQueued(sourceProvider, source, targetProvider, target));
1199
+ }
1200
+ async doPipeUnbufferedToBufferedQueued(sourceProvider, source, targetProvider, target) {
1201
+ // Open handle
1202
+ const targetHandle = await targetProvider.open(target, { create: true });
1203
+ // Read entire buffer from source and write buffered
1204
+ try {
1205
+ const buffer = await sourceProvider.readFile(source);
1206
+ await this.doWriteBuffer(targetProvider, targetHandle, buffer_1.BinaryBuffer.wrap(buffer), buffer.byteLength, 0, 0);
1207
+ }
1208
+ catch (error) {
1209
+ throw (0, files_1.ensureFileSystemProviderError)(error);
1210
+ }
1211
+ finally {
1212
+ await targetProvider.close(targetHandle);
1213
+ }
1214
+ }
1215
+ async doPipeBufferedToUnbuffered(sourceProvider, source, targetProvider, target) {
1216
+ // Read buffer via stream buffered
1217
+ const buffer = await buffer_1.BinaryBufferReadableStream.toBuffer(this.readFileBuffered(sourceProvider, source, cancellation_1.CancellationToken.None));
1218
+ // Write buffer into target at once
1219
+ await this.doWriteUnbuffered(targetProvider, target, buffer);
1220
+ }
1221
+ throwIfFileSystemIsReadonly(provider, resource) {
1222
+ if (provider.capabilities & 2048 /* Readonly */) {
1223
+ throw new files_1.FileOperationError(core_1.nls.localizeByDefault("Unable to modify read-only file '{0}'", this.resourceForError(resource)), 6 /* FILE_PERMISSION_DENIED */);
1224
+ }
1225
+ return provider;
1226
+ }
1227
+ resourceForError(resource) {
1228
+ return this.labelProvider.getLongName(resource);
1229
+ }
1230
+ addFileOperationParticipant(participant) {
1231
+ this.participants.push(participant);
1232
+ return disposable_1.Disposable.create(() => {
1233
+ const index = this.participants.indexOf(participant);
1234
+ if (index > -1) {
1235
+ this.participants.splice(index, 1);
1236
+ }
1237
+ });
1238
+ }
1239
+ async runFileOperationParticipants(target, source, operation) {
1240
+ const participantsTimeout = this.preferences['files.participants.timeout'];
1241
+ if (participantsTimeout <= 0 || this.participants.length === 0) {
1242
+ return;
1243
+ }
1244
+ const cancellationTokenSource = new cancellation_1.CancellationTokenSource();
1245
+ return this.progressService.withProgress(this.progressLabel(operation), 'notification', async () => {
1246
+ for (const participant of this.participants) {
1247
+ if (cancellationTokenSource.token.isCancellationRequested) {
1248
+ break;
1249
+ }
1250
+ try {
1251
+ const promise = participant.participate(target, source, operation, participantsTimeout, cancellationTokenSource.token);
1252
+ await Promise.race([
1253
+ promise,
1254
+ (0, promise_util_1.timeout)(participantsTimeout, cancellationTokenSource.token).then(() => cancellationTokenSource.dispose(), () => { })
1255
+ ]);
1256
+ }
1257
+ catch (err) {
1258
+ console.warn(err);
1259
+ }
1260
+ }
1261
+ }, () => {
1262
+ cancellationTokenSource.cancel();
1263
+ });
1264
+ }
1265
+ progressLabel(operation) {
1266
+ switch (operation) {
1267
+ case 0 /* CREATE */:
1268
+ return core_1.nls.localizeByDefault("Running 'File Create' participants...");
1269
+ case 2 /* MOVE */:
1270
+ return core_1.nls.localizeByDefault("Running 'File Rename' participants...");
1271
+ case 3 /* COPY */:
1272
+ return core_1.nls.localizeByDefault("Running 'File Copy' participants...");
1273
+ case 1 /* DELETE */:
1274
+ return core_1.nls.localizeByDefault("Running 'File Delete' participants...");
1275
+ }
1276
+ }
1277
+ // #endregion
1278
+ // #region encoding
1279
+ async getWriteEncoding(resource, options) {
1280
+ const encoding = await this.getEncodingForResource(resource, options ? options.encoding : undefined);
1281
+ return this.encodingService.toResourceEncoding(encoding, {
1282
+ overwriteEncoding: options === null || options === void 0 ? void 0 : options.overwriteEncoding,
1283
+ read: async (length) => {
1284
+ const buffer = await buffer_1.BinaryBufferReadableStream.toBuffer((await this.readFileStream(resource, { length })).value);
1285
+ return buffer.buffer;
1286
+ }
1287
+ });
1288
+ }
1289
+ getReadEncoding(resource, options, detectedEncoding) {
1290
+ let preferredEncoding;
1291
+ // Encoding passed in as option
1292
+ if (options === null || options === void 0 ? void 0 : options.encoding) {
1293
+ if (detectedEncoding === encodings_1.UTF8_with_bom && options.encoding === encodings_1.UTF8) {
1294
+ preferredEncoding = encodings_1.UTF8_with_bom; // indicate the file has BOM if we are to resolve with UTF 8
1295
+ }
1296
+ else {
1297
+ preferredEncoding = options.encoding; // give passed in encoding highest priority
1298
+ }
1299
+ }
1300
+ else if (detectedEncoding) {
1301
+ preferredEncoding = detectedEncoding;
1302
+ }
1303
+ return this.getEncodingForResource(resource, preferredEncoding);
1304
+ }
1305
+ async getEncodingForResource(resource, preferredEncoding) {
1306
+ resource = await this.toUnderlyingResource(resource);
1307
+ return this.encodingRegistry.getEncodingForResource(resource, preferredEncoding);
1308
+ }
1309
+ /**
1310
+ * Converts to an underlying fs provider resource format.
1311
+ *
1312
+ * For example converting `user-storage` resources to `file` resources under a user home:
1313
+ * user-storage:/user/settings.json => file://home/.theia/settings.json
1314
+ */
1315
+ async toUnderlyingResource(resource) {
1316
+ let provider = await this.withProvider(resource);
1317
+ while (provider instanceof delegating_file_system_provider_1.DelegatingFileSystemProvider) {
1318
+ resource = provider.toUnderlyingResource(resource);
1319
+ provider = await this.withProvider(resource);
1320
+ }
1321
+ return resource;
1322
+ }
1323
+ // #endregion
1324
+ handleFileWatchError() {
1325
+ this.watcherErrorHandler.handleError();
1326
+ }
1327
+ };
1328
+ (0, tslib_1.__decorate)([
1329
+ (0, inversify_1.inject)(label_provider_1.LabelProvider),
1330
+ (0, tslib_1.__metadata)("design:type", label_provider_1.LabelProvider)
1331
+ ], FileService.prototype, "labelProvider", void 0);
1332
+ (0, tslib_1.__decorate)([
1333
+ (0, inversify_1.inject)(filesystem_preferences_1.FileSystemPreferences),
1334
+ (0, tslib_1.__metadata)("design:type", Object)
1335
+ ], FileService.prototype, "preferences", void 0);
1336
+ (0, tslib_1.__decorate)([
1337
+ (0, inversify_1.inject)(progress_service_1.ProgressService),
1338
+ (0, tslib_1.__metadata)("design:type", progress_service_1.ProgressService)
1339
+ ], FileService.prototype, "progressService", void 0);
1340
+ (0, tslib_1.__decorate)([
1341
+ (0, inversify_1.inject)(encoding_registry_1.EncodingRegistry),
1342
+ (0, tslib_1.__metadata)("design:type", encoding_registry_1.EncodingRegistry)
1343
+ ], FileService.prototype, "encodingRegistry", void 0);
1344
+ (0, tslib_1.__decorate)([
1345
+ (0, inversify_1.inject)(encoding_service_1.EncodingService),
1346
+ (0, tslib_1.__metadata)("design:type", encoding_service_1.EncodingService)
1347
+ ], FileService.prototype, "encodingService", void 0);
1348
+ (0, tslib_1.__decorate)([
1349
+ (0, inversify_1.inject)(contribution_provider_1.ContributionProvider),
1350
+ (0, inversify_1.named)(exports.FileServiceContribution),
1351
+ (0, tslib_1.__metadata)("design:type", Object)
1352
+ ], FileService.prototype, "contributions", void 0);
1353
+ (0, tslib_1.__decorate)([
1354
+ (0, inversify_1.inject)(filesystem_watcher_error_handler_1.FileSystemWatcherErrorHandler),
1355
+ (0, tslib_1.__metadata)("design:type", filesystem_watcher_error_handler_1.FileSystemWatcherErrorHandler)
1356
+ ], FileService.prototype, "watcherErrorHandler", void 0);
1357
+ (0, tslib_1.__decorate)([
1358
+ (0, inversify_1.postConstruct)(),
1359
+ (0, tslib_1.__metadata)("design:type", Function),
1360
+ (0, tslib_1.__metadata)("design:paramtypes", []),
1361
+ (0, tslib_1.__metadata)("design:returntype", void 0)
1362
+ ], FileService.prototype, "init", null);
1363
+ FileService = (0, tslib_1.__decorate)([
1364
+ (0, inversify_1.injectable)()
1365
+ ], FileService);
1366
+ exports.FileService = FileService;
1367
1367
  //# sourceMappingURL=file-service.js.map