From 6075dbaaeded16d5a48f677bc7cf50af84491614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Lopes?= Date: Sat, 20 Jul 2024 17:55:24 +0100 Subject: [PATCH] Fix microsoft/vscode#209655: fix case-sensitive JSON sorting error --- src/test/sort.test.ts | 48 +++++++++++++++++++++++++++++++++++++++++++ src/utils/sort.ts | 10 +++++++++ 2 files changed, 58 insertions(+) diff --git a/src/test/sort.test.ts b/src/test/sort.test.ts index 6c99016..95f2a00 100644 --- a/src/test/sort.test.ts +++ b/src/test/sort.test.ts @@ -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); + }); }); diff --git a/src/utils/sort.ts b/src/utils/sort.ts index 83ef174..5b5758a 100644 --- a/src/utils/sort.ts +++ b/src/utils/sort.ts @@ -376,6 +376,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; @@ -390,6 +398,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) {