Skip to content

Commit

Permalink
Merge pull request #238 from ttlopes/fix-json-sort
Browse files Browse the repository at this point in the history
Fix microsoft/vscode#209655: fix case-sensitive JSON sorting error
  • Loading branch information
aeschli authored Aug 26, 2024
2 parents 24678bd + 6075dba commit bf616c2
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/test/sort.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1435,4 +1435,52 @@ suite('Sort JSON', () => {

testSort(content, expected, formattingOptions);
});

test('sorting a JSON object with mixed case keys', () => {
const content = [
'{',
' "tEst": "tEst",',
' "tesT": "tesT",',
' "teSt": "teSt",',
' "Test": "Test",',
' "test": "test"',
'}'
].join('\n');

const expected = [
'{',
' "Test": "Test",',
' "tEst": "tEst",',
' "teSt": "teSt",',
' "tesT": "tesT",',
' "test": "test"',
'}'
].join('\n');

testSort(content, expected, formattingOptions);
});

test('sorting an already sorted JSON object with mixed case keys', () => {
const content = [
'{',
' "Test": "Test",',
' "tEst": "tEst",',
' "teSt": "teSt",',
' "tesT": "tesT",',
' "test": "test"',
'}'
].join('\n');

const expected = [
'{',
' "Test": "Test",',
' "tEst": "tEst",',
' "teSt": "teSt",',
' "tesT": "tesT",',
' "test": "test"',
'}'
].join('\n');

testSort(content, expected, formattingOptions);
});
});
10 changes: 10 additions & 0 deletions src/utils/sort.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,14 @@ function sortJsoncDocument(jsonDocument: TextDocument, propertyTree: PropertyTre
return sortedJsonDocument;
}

function sortPropertiesCaseSensitive(properties: PropertyTree[]): void {
properties.sort((a, b) => {
const aName = a.propertyName ?? '';
const bName = b.propertyName ?? '';
return aName < bName ? -1 : aName > bName ? 1 : 0;
});
}

function updateSortingQueue(queue: any[], propertyTree: PropertyTree, beginningLineNumber: number) {
if (propertyTree.childrenProperties.length === 0) {
return;
Expand All @@ -389,6 +397,8 @@ function updateSortingQueue(queue: any[], propertyTree: PropertyTree, beginningL
const diff = minimumBeginningLineNumber - propertyTree.beginningLineNumber!;
beginningLineNumber = beginningLineNumber + diff;

sortPropertiesCaseSensitive(propertyTree.childrenProperties);

queue.push(new SortingRange(beginningLineNumber, propertyTree.childrenProperties));

} else if (propertyTree.type === Container.Array) {
Expand Down

0 comments on commit bf616c2

Please sign in to comment.