Skip to content

Commit

Permalink
Ensure text changes are applied in order (#42)
Browse files Browse the repository at this point in the history
* ensure correct text change order

* Actually impl test

* fix formatting

* formatting
  • Loading branch information
phillipb authored Jan 17, 2025
1 parent fb8f136 commit 13e499e
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,33 @@ function getFileTextChangesFromCodeFix(codefix: CodeFixAction): readonly FileTex
return codefix.changes;
}

function mergeChanges(arr1: TextChange[], arr2: TextChange[]): TextChange[] {
let mergedArray = [];
let i = 0;
let j = 0;

while (i < arr1.length && j < arr2.length) {
if (arr1[i].span.start < arr2[j].span.start) {
mergedArray.push(arr1[i]);
i++;
} else {
mergedArray.push(arr2[j]);
j++;
}
}

while (i < arr1.length) {
mergedArray.push(arr1[i]);
i++;
}

while (j < arr2.length) {
mergedArray.push(arr2[j]);
j++;
}

return mergedArray;
}
export function getTextChangeDict(codefixes: readonly CodeFixAction[]): Map<string, TextChange[]> {
let textChangeDict = new Map<string, TextChange[]>();

Expand All @@ -473,7 +500,7 @@ export function getTextChangeDict(codefixes: readonly CodeFixAction[]): Map<stri
if (prevVal === undefined) {
textChangeDict.set(key, value);
} else {
textChangeDict.set(key, prevVal.concat(value));
textChangeDict.set(key, mergeChanges(prevVal, value));
}
}
}
Expand Down
34 changes: 34 additions & 0 deletions test/unit/getTextChangeDict.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { getTextChangeDict } from "../../src/index";
import { CodeFixAction } from "typescript";

const codefixes: CodeFixAction[] = [
{
fixName: 'fixOverrideModifier',
description: 'Add \'override\' modifier',
changes: [{ fileName: 'foo.ts', textChanges: [{ span: { start: 2, length: 0 }, newText: 'override ' }, { span: { start: 3, length: 0 }, newText: 'override ' }] }],
commands: undefined,
fixId: 'fixAddOverrideModifier'
},
{
fixName: 'fixOverrideModifier',
description: 'Add \'override\' modifier',
changes: [{ fileName: 'foo.ts', textChanges: [{ span: { start: 1, length: 0 }, newText: 'override ' }] }],
commands: undefined,
fixId: 'fixAddOverrideModifier'
},
{
fixName: 'addConvertToUnknownForNonOverlappingTypes',
description: 'Add \'unknown\' conversion for non-overlapping types',
changes: [{ fileName: 'foo.ts', textChanges: [{ span: { start: 8, length: 9 }, newText: '<unknown>["words"]' }] }],
commands: undefined,
fixId: 'addConvertToUnknownForNonOverlappingTypes'
},
]

test("should merge text changes in order", () => {
const result = getTextChangeDict(codefixes);
const changes = result.get('foo.ts');
const spanStarts = changes?.map(c => c.span.start);
expect(spanStarts).toEqual([1, 2, 3, 8]);
})

0 comments on commit 13e499e

Please sign in to comment.