From 0cd7ec7953c98a6808b2cdc0d118fb48ff6a1367 Mon Sep 17 00:00:00 2001 From: Stephen Zhou Date: Wed, 15 May 2024 19:45:24 +0800 Subject: [PATCH] fix: support tab indent (#318) * fix: support tab indent * chore: update --- index.js | 6 ++++-- tests/main.js | 10 ++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 660b16fe..8c932512 100755 --- a/index.js +++ b/index.js @@ -380,12 +380,14 @@ const overFields = pipe( function editStringJSON(json, over) { if (typeof json === 'string') { - const { indent } = detectIndent(json) + const { indent, type } = detectIndent(json) const endCharacters = json.slice(-1) === '\n' ? '\n' : '' const newline = detectNewline(json) json = JSON.parse(json) - let result = JSON.stringify(over(json), null, indent) + endCharacters + let result = + JSON.stringify(over(json), null, type === 'tab' ? '\t' : indent) + + endCharacters if (newline === '\r\n') { result = result.replace(/\n/g, newline) } diff --git a/tests/main.js b/tests/main.js index d86355fc..6c2952cf 100644 --- a/tests/main.js +++ b/tests/main.js @@ -17,6 +17,16 @@ test('main', (t) => { '{"name":"sort-package-json","version":"1.0.0"}', 'Accepts string, returns sorted string', ) + t.is( + sortPackageJson(JSON.stringify(packageJson, null, 4)), + '{\n "name": "sort-package-json",\n "version": "1.0.0"\n}', + 'Detect indent', + ) + t.is( + sortPackageJson(JSON.stringify(packageJson, null, '\t')), + '{\n\t"name": "sort-package-json",\n\t"version": "1.0.0"\n}', + 'Detect tab indent', + ) const array = ['foo', 'bar'] const string = JSON.stringify(array)