Skip to content

Commit

Permalink
fix: support tab indent (#318)
Browse files Browse the repository at this point in the history
* fix: support tab indent

* chore: update
  • Loading branch information
hyoban authored May 15, 2024
1 parent a55cbb7 commit 0cd7ec7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
10 changes: 10 additions & 0 deletions tests/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 0cd7ec7

Please sign in to comment.