@theia/filesystem 1.45.1 → 1.46.0-next.72

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