@theia/filesystem 1.34.2 → 1.34.3

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