-
Notifications
You must be signed in to change notification settings - Fork 382
/
workspace-edit.service.ts
354 lines (319 loc) · 11.8 KB
/
workspace-edit.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import { runInAction } from 'mobx';
import { Injectable, Autowired } from '@opensumi/di';
import { URI, IEventBus, isWindows, isUndefined } from '@opensumi/ide-core-browser';
import { WorkbenchEditorService } from '@opensumi/ide-editor';
import { IEditorDocumentModelService, IResource, isDiffResource } from '@opensumi/ide-editor/lib/browser';
import { EditorGroup } from '@opensumi/ide-editor/lib/browser/workbench-editor.service';
import { FileSystemError } from '@opensumi/ide-file-service/lib/common';
import { EndOfLineSequence, EOL } from '@opensumi/ide-monaco/lib/browser/monaco-api/types';
import { Range } from '@opensumi/monaco-editor-core/esm/vs/editor/common/core/range';
import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api';
import {
IResourceTextEdit,
IWorkspaceEditService,
IWorkspaceEdit,
IResourceFileEdit,
WorkspaceEditDidRenameFileEvent,
WorkspaceEditDidDeleteFileEvent,
IWorkspaceFileService,
} from '../common';
type WorkspaceEdit = ResourceTextEditTask | ResourceFileEdit;
@Injectable()
export class WorkspaceEditServiceImpl implements IWorkspaceEditService {
private editStack: BulkEdit[] = [];
@Autowired(IEditorDocumentModelService)
documentModelService: IEditorDocumentModelService;
@Autowired(IWorkspaceFileService)
workspaceFileService: IWorkspaceFileService;
@Autowired()
editorService: WorkbenchEditorService;
@Autowired(IEventBus)
eventBus: IEventBus;
async apply(edit: IWorkspaceEdit): Promise<void> {
const bulkEdit = new BulkEdit();
edit.edits.forEach((edit) => {
bulkEdit.add(edit);
});
await bulkEdit.apply(this.documentModelService, this.editorService, this.workspaceFileService, this.eventBus);
this.editStack.push(bulkEdit);
}
revertTopFileEdit(): Promise<void> {
throw new Error('Method not implemented.');
}
}
export class BulkEdit {
private edits: WorkspaceEdit[] = [];
async apply(
documentModelService: IEditorDocumentModelService,
editorService: WorkbenchEditorService,
workspaceFS: IWorkspaceFileService,
eventBus: IEventBus,
) {
for (const edit of this.edits) {
if (edit instanceof ResourceFileEdit) {
await edit.apply(documentModelService, editorService, workspaceFS, eventBus);
} else {
await edit.apply(documentModelService, editorService);
}
}
}
add(edit: IResourceTextEdit | IResourceFileEdit) {
if (isResourceFileEdit(edit)) {
this.edits.push(new ResourceFileEdit(edit));
} else {
const last = this.edits[this.edits.length - 1];
const textEdit = edit as IResourceTextEdit;
if (last && !isResourceFileEdit(last)) {
// 合并连续同目标的edits
if (last.resource.toString() === textEdit.resource.toString()) {
let shouldMerge = false;
if (last.versionId) {
if (textEdit.versionId) {
shouldMerge = textEdit.versionId === last.versionId;
} else {
shouldMerge = true;
}
} else {
if (!textEdit.versionId) {
shouldMerge = true;
}
}
if (shouldMerge) {
last.addEdit(edit as IResourceTextEdit);
return;
}
}
}
this.edits.push(new ResourceTextEditTask(edit as IResourceTextEdit));
}
}
revert(onlyFileEdits: true) {}
}
export class ResourceTextEditTask {
public edits: IResourceTextEdit[];
public resource: URI;
public versionId: number | undefined;
public options: {
openDirtyInEditor?: boolean;
dirtyIfInEditor?: boolean;
} = {};
constructor(edit: IResourceTextEdit) {
this.resource = edit.resource;
this.versionId = edit.versionId;
this.options = edit.options || {};
this.edits = [edit];
}
addEdit(edit: IResourceTextEdit) {
this.edits.push(edit);
}
async apply(documentModelService: IEditorDocumentModelService, editorService: WorkbenchEditorService) {
const docRef = await documentModelService.createModelReference(this.resource, 'bulk-edit');
const documentModel = docRef.instance;
const monacoModel = documentModel.getMonacoModel();
if (this.versionId) {
if (monacoModel.getVersionId() !== this.versionId) {
throw new Error('文档版本不一致,无法执行变更');
}
}
const edits: monaco.editor.IIdentifiedSingleEditOperation[] = [];
let newEOL: EndOfLineSequence | undefined;
for (const edit of this.edits) {
if (edit.textEdit.eol && !isUndefined(edit.textEdit.eol)) {
newEOL = edit.textEdit.eol;
}
edits.push({
forceMoveMarkers: false,
range: Range.lift(edit.textEdit.range),
text: edit.textEdit.text,
});
}
if (edits.length > 0) {
monacoModel.pushStackElement();
monacoModel.pushEditOperations(null, edits, () => null);
monacoModel.pushStackElement();
}
if (newEOL && !isUndefined(newEOL)) {
monacoModel.pushStackElement();
documentModel.eol = newEOL === EndOfLineSequence.CRLF ? EOL.CRLF : EOL.LF;
monacoModel.pushStackElement();
}
const shouldSave = await this.editorOperation(editorService);
if (shouldSave) {
documentModel.save();
}
docRef.dispose();
}
// 返回是否保存
private async editorOperation(editorService: WorkbenchEditorService): Promise<boolean> {
if (this.options.openDirtyInEditor) {
for (const group of editorService.editorGroups) {
if (group.resources.findIndex((r) => isDocumentUriInResource(r, this.resource)) !== -1) {
return false;
}
}
editorService.open(this.resource, { backend: true });
return false;
} else if (this.options.dirtyIfInEditor) {
for (const group of editorService.editorGroups) {
if (group.resources.findIndex((r) => isDocumentUriInResource(r, this.resource)) !== -1) {
return false;
}
}
}
return true;
}
async revert(): Promise<void> {}
}
export class ResourceFileEdit implements IResourceFileEdit {
oldResource?: URI;
newResource?: URI;
options: {
overwrite?: boolean | undefined;
ignoreIfNotExists?: boolean | undefined;
recursive?: boolean | undefined;
showInEditor?: boolean;
isDirectory?: boolean;
copy?: boolean;
ignoreIfExists?: boolean | undefined;
content?: string;
} = {};
constructor(edit: IResourceFileEdit) {
this.oldResource = edit.oldResource;
this.newResource = edit.newResource;
this.options = edit.options;
}
async notifyEditor(editorService: WorkbenchEditorService, documentModelService: IEditorDocumentModelService) {
if (this.oldResource && this.newResource) {
const promises: Promise<any>[] = [];
const urisToDealWith: Set<string> = new Set();
editorService.editorGroups.forEach((g) => {
g.resources.forEach((r) => {
if (this.oldResource!.isEqualOrParent(r.uri)) {
urisToDealWith.add(r.uri.toString());
}
});
});
urisToDealWith.forEach((uriString) => {
const oldResource = new URI(uriString);
const subPath = uriString.substr(this.oldResource!.toString().length);
const newResource = new URI(this.newResource!.toString()! + subPath);
promises.push(this.notifyOnResource(oldResource, newResource, editorService, documentModelService));
});
return Promise.all(promises);
}
}
async notifyOnResource(
oldResource: URI,
newResource: URI,
editorService: WorkbenchEditorService,
documentModelService: IEditorDocumentModelService,
) {
const docRef = documentModelService.getModelReference(oldResource, 'bulk-file-move');
let dirtyContent: string | undefined;
let dirtyEOL: EOL | undefined;
if (docRef && docRef.instance.dirty) {
dirtyContent = docRef.instance.getText();
dirtyEOL = docRef.instance.eol;
await docRef.instance.revert(true);
}
if (docRef) {
docRef.dispose();
}
// 如果之前的文件在编辑器中被打开,重新打开文件
await Promise.all([
editorService.editorGroups.map(async (g) => {
const index = g.resources.findIndex((r) => r.uri.isEqual(oldResource));
if (index !== -1) {
await runInAction(async () => {
await g.open(newResource, {
index,
backend: !(g.currentResource && g.currentResource.uri.isEqual(oldResource)),
// 如果旧的是preview模式,应该保持,如果不是,应该不要关闭其他处于preview模式的资源tab
preview: (g as EditorGroup).previewURI ? (g as EditorGroup).previewURI!.isEqual(oldResource) : false,
});
await g.close(oldResource);
});
}
}),
]);
if (dirtyContent) {
const newDocRef = await documentModelService.createModelReference(newResource, 'bulk-file-move');
newDocRef.instance.updateContent(dirtyContent, dirtyEOL);
newDocRef.dispose();
}
}
async apply(
documentModelService: IEditorDocumentModelService,
editorService: WorkbenchEditorService,
workspaceFS: IWorkspaceFileService,
eventBus: IEventBus,
) {
const options = this.options || {};
if (this.newResource && this.oldResource) {
if (options.copy) {
await workspaceFS.copy([{ source: this.oldResource.codeUri, target: this.newResource.codeUri }], options);
} else {
// rename
await workspaceFS.move([{ source: this.oldResource.codeUri, target: this.newResource.codeUri }], options);
await this.notifyEditor(editorService, documentModelService);
// TODO: 文件夹rename应该带传染性, 但是遍历实现比较坑,先不实现
eventBus.fire(new WorkspaceEditDidRenameFileEvent({ oldUri: this.oldResource, newUri: this.newResource }));
}
if (options.showInEditor) {
editorService.open(this.newResource);
}
} else if (!this.newResource && this.oldResource) {
// 删除文件
try {
// electron windows下moveToTrash大量文件会导致IDE卡死,如果检测到这个情况就不使用moveToTrash
await workspaceFS.delete([this.oldResource], {
useTrash: !(isWindows && this.oldResource.path.name === 'node_modules'),
});
// 默认recursive
await editorService.close(this.oldResource, true);
eventBus.fire(new WorkspaceEditDidDeleteFileEvent({ oldUri: this.oldResource }));
} catch (err) {
if (FileSystemError.FileNotFound.is(err) && options.ignoreIfNotExists) {
// 不抛出错误
} else {
throw err;
}
}
} else if (this.newResource && !this.oldResource) {
// 创建文件
try {
if (options.isDirectory) {
await workspaceFS.createFolder(this.newResource);
} else {
await workspaceFS.create(this.newResource, options.content || '', { overwrite: options.overwrite });
}
} catch (err) {
if (FileSystemError.FileExists.is(err) && options.ignoreIfExists) {
// 不抛出错误
} else {
throw err;
}
}
if (!options.isDirectory && options.showInEditor) {
editorService.open(this.newResource);
}
}
}
async revert(): Promise<void> {}
}
export function isResourceFileEdit(thing: any): thing is ResourceFileEdit {
return !!(thing as ResourceFileEdit).newResource || !!(thing as ResourceFileEdit).oldResource;
}
/**
* 当前编辑器的文档是否在指定的编辑器 resource (tab) 中
* 此处需要额外判断一下 diffEditor 的情况
* @param resource
* @param uri
*/
function isDocumentUriInResource(resource: IResource<any>, uri: URI) {
if (isDiffResource(resource)) {
return resource.metadata?.modified.isEqual(uri) || resource.metadata?.original.isEqual(uri);
} else {
return resource.uri.isEqual(uri);
}
}