-
Notifications
You must be signed in to change notification settings - Fork 27.9k
/
replaceService.ts
228 lines (201 loc) · 10.3 KB
/
replaceService.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { URI } from 'vs/base/common/uri';
import * as network from 'vs/base/common/network';
import { Disposable } from 'vs/base/common/lifecycle';
import { IReplaceService } from 'vs/workbench/contrib/search/browser/replace';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IModelService } from 'vs/editor/common/services/model';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { Match, FileMatch, FileMatchOrMatch, ISearchWorkbenchService, NotebookMatch } from 'vs/workbench/contrib/search/browser/searchModel';
import { IProgress, IProgressStep } from 'vs/platform/progress/common/progress';
import { ITextModelService, ITextModelContentProvider } from 'vs/editor/common/services/resolverService';
import { IWorkbenchContribution } from 'vs/workbench/common/contributions';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { ITextModel } from 'vs/editor/common/model';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { createTextBufferFactoryFromSnapshot } from 'vs/editor/common/model/textModel';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IBulkEditService, ResourceTextEdit } from 'vs/editor/browser/services/bulkEditService';
import { Range } from 'vs/editor/common/core/range';
import { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation';
import { ILabelService } from 'vs/platform/label/common/label';
import { dirname } from 'vs/base/common/resources';
import { Promises } from 'vs/base/common/async';
import { SaveSourceRegistry } from 'vs/workbench/common/editor';
import { CellUri } from 'vs/workbench/contrib/notebook/common/notebookCommon';
const REPLACE_PREVIEW = 'replacePreview';
const toReplaceResource = (fileResource: URI): URI => {
return fileResource.with({ scheme: network.Schemas.internal, fragment: REPLACE_PREVIEW, query: JSON.stringify({ scheme: fileResource.scheme }) });
};
const toFileResource = (replaceResource: URI): URI => {
return replaceResource.with({ scheme: JSON.parse(replaceResource.query)['scheme'], fragment: '', query: '' });
};
export class ReplacePreviewContentProvider implements ITextModelContentProvider, IWorkbenchContribution {
constructor(
@IInstantiationService private readonly instantiationService: IInstantiationService,
@ITextModelService private readonly textModelResolverService: ITextModelService
) {
this.textModelResolverService.registerTextModelContentProvider(network.Schemas.internal, this);
}
provideTextContent(uri: URI): Promise<ITextModel> | null {
if (uri.fragment === REPLACE_PREVIEW) {
return this.instantiationService.createInstance(ReplacePreviewModel).resolve(uri);
}
return null;
}
}
class ReplacePreviewModel extends Disposable {
constructor(
@IModelService private readonly modelService: IModelService,
@ILanguageService private readonly languageService: ILanguageService,
@ITextModelService private readonly textModelResolverService: ITextModelService,
@IReplaceService private readonly replaceService: IReplaceService,
@ISearchWorkbenchService private readonly searchWorkbenchService: ISearchWorkbenchService
) {
super();
}
async resolve(replacePreviewUri: URI): Promise<ITextModel> {
const fileResource = toFileResource(replacePreviewUri);
const fileMatch = <FileMatch>this.searchWorkbenchService.searchModel.searchResult.matches().filter(match => match.resource.toString() === fileResource.toString())[0];
const ref = this._register(await this.textModelResolverService.createModelReference(fileResource));
const sourceModel = ref.object.textEditorModel;
const sourceModelLanguageId = sourceModel.getLanguageId();
const replacePreviewModel = this.modelService.createModel(createTextBufferFactoryFromSnapshot(sourceModel.createSnapshot()), this.languageService.createById(sourceModelLanguageId), replacePreviewUri);
this._register(fileMatch.onChange(({ forceUpdateModel }) => this.update(sourceModel, replacePreviewModel, fileMatch, forceUpdateModel)));
this._register(this.searchWorkbenchService.searchModel.onReplaceTermChanged(() => this.update(sourceModel, replacePreviewModel, fileMatch)));
this._register(fileMatch.onDispose(() => replacePreviewModel.dispose())); // TODO@Sandeep we should not dispose a model directly but rather the reference (depends on https://github.com/microsoft/vscode/issues/17073)
this._register(replacePreviewModel.onWillDispose(() => this.dispose()));
this._register(sourceModel.onWillDispose(() => this.dispose()));
return replacePreviewModel;
}
private update(sourceModel: ITextModel, replacePreviewModel: ITextModel, fileMatch: FileMatch, override: boolean = false): void {
if (!sourceModel.isDisposed() && !replacePreviewModel.isDisposed()) {
this.replaceService.updateReplacePreview(fileMatch, override);
}
}
}
export class ReplaceService implements IReplaceService {
declare readonly _serviceBrand: undefined;
private static readonly REPLACE_SAVE_SOURCE = SaveSourceRegistry.registerSource('searchReplace.source', nls.localize('searchReplace.source', "Search and Replace"));
constructor(
@ITextFileService private readonly textFileService: ITextFileService,
@IEditorService private readonly editorService: IEditorService,
@ITextModelService private readonly textModelResolverService: ITextModelService,
@IBulkEditService private readonly bulkEditorService: IBulkEditService,
@ILabelService private readonly labelService: ILabelService
) { }
replace(match: Match): Promise<any>;
replace(files: FileMatch[], progress?: IProgress<IProgressStep>): Promise<any>;
replace(match: FileMatchOrMatch, progress?: IProgress<IProgressStep>, resource?: URI): Promise<any>;
async replace(arg: any, progress: IProgress<IProgressStep> | undefined = undefined, resource: URI | null = null): Promise<any> {
const edits = this.createEdits(arg, resource);
await this.bulkEditorService.apply(edits, { progress });
const rawTextPromises = edits.map(async e => {
if (e.resource.scheme === network.Schemas.vscodeNotebookCell) {
const notebookResource = CellUri.parse(e.resource)?.notebook;
if (notebookResource) {
return this.editorService.save([...this.editorService.findEditors(notebookResource)]);
} else {
return Promise.resolve();
}
} else {
return this.textFileService.files.get(e.resource)?.save({ source: ReplaceService.REPLACE_SAVE_SOURCE });
}
});
return Promises.settled(rawTextPromises);
}
async openReplacePreview(element: FileMatchOrMatch, preserveFocus?: boolean, sideBySide?: boolean, pinned?: boolean): Promise<any> {
const fileMatch = element instanceof Match ? element.parent() : element;
const editor = await this.editorService.openEditor({
original: { resource: fileMatch.resource },
modified: { resource: toReplaceResource(fileMatch.resource) },
label: nls.localize('fileReplaceChanges', "{0} ↔ {1} (Replace Preview)", fileMatch.name(), fileMatch.name()),
description: this.labelService.getUriLabel(dirname(fileMatch.resource), { relative: true }),
options: {
preserveFocus,
pinned,
revealIfVisible: true
}
});
const input = editor?.input;
const disposable = fileMatch.onDispose(() => {
input?.dispose();
disposable.dispose();
});
await this.updateReplacePreview(fileMatch);
if (editor) {
const editorControl = editor.getControl();
if (element instanceof Match && editorControl) {
editorControl.revealLineInCenter(element.range().startLineNumber, ScrollType.Immediate);
}
}
}
async updateReplacePreview(fileMatch: FileMatch, override: boolean = false): Promise<void> {
const replacePreviewUri = toReplaceResource(fileMatch.resource);
const [sourceModelRef, replaceModelRef] = await Promise.all([this.textModelResolverService.createModelReference(fileMatch.resource), this.textModelResolverService.createModelReference(replacePreviewUri)]);
const sourceModel = sourceModelRef.object.textEditorModel;
const replaceModel = replaceModelRef.object.textEditorModel;
// If model is disposed do not update
try {
if (sourceModel && replaceModel) {
if (override) {
replaceModel.setValue(sourceModel.getValue());
} else {
replaceModel.undo();
}
this.applyEditsToPreview(fileMatch, replaceModel);
}
} finally {
sourceModelRef.dispose();
replaceModelRef.dispose();
}
}
private applyEditsToPreview(fileMatch: FileMatch, replaceModel: ITextModel): void {
const resourceEdits = this.createEdits(fileMatch, replaceModel.uri);
const modelEdits: ISingleEditOperation[] = [];
for (const resourceEdit of resourceEdits) {
modelEdits.push(EditOperation.replaceMove(
Range.lift(resourceEdit.textEdit.range),
resourceEdit.textEdit.text)
);
}
replaceModel.pushEditOperations([], modelEdits.sort((a, b) => Range.compareRangesUsingStarts(a.range, b.range)), () => []);
}
private createEdits(arg: FileMatchOrMatch | FileMatch[], resource: URI | null = null): ResourceTextEdit[] {
const edits: ResourceTextEdit[] = [];
if (arg instanceof Match) {
if (arg instanceof NotebookMatch) {
const match = <NotebookMatch>arg;
edits.push(this.createEdit(match, match.replaceString, match.cell.uri));
} else {
const match = <Match>arg;
edits.push(this.createEdit(match, match.replaceString, resource));
}
}
if (arg instanceof FileMatch) {
arg = [arg];
}
if (arg instanceof Array) {
arg.forEach(element => {
const fileMatch = <FileMatch>element;
if (fileMatch.count() > 0) {
edits.push(...fileMatch.matches().map(
match => this.createEdit(match, match.replaceString, (match instanceof NotebookMatch) ? match.cell.uri : resource)
));
}
});
}
return edits;
}
private createEdit(match: Match, text: string, resource: URI | null = null): ResourceTextEdit {
const fileMatch: FileMatch = match.parent();
return new ResourceTextEdit(
resource ?? fileMatch.resource,
{ range: match.range(), text }, undefined, undefined
);
}
}