Skip to content

Commit

Permalink
feat: new eol detection (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker authored and keithamus committed Dec 10, 2019
1 parent a91a766 commit 425352e
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 10 deletions.
12 changes: 6 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env node
const _sortObjectKeys = require('sort-object-keys')
const detectIndent = require('detect-indent')
const detectNewline = require('detect-newline').graceful
const glob = require('glob')
const sortObjectKeys = comp => x => _sortObjectKeys(x, comp)

Expand Down Expand Up @@ -119,15 +120,14 @@ const sortOrder = fields.map(({ key }) => key)

function editStringJSON(json, over) {
if (typeof json === 'string') {
const indentLevel = detectIndent(json).indent
const { indent } = detectIndent(json)
const endCharacters = json.slice(-1) === '\n' ? '\n' : ''
const newlineMatch = json.match(/(\r?\n)/)
const hasWindowsNewlines = (newlineMatch && newlineMatch[0]) === '\r\n'
const newline = detectNewline(json)
json = JSON.parse(json)

let result = JSON.stringify(over(json), null, indentLevel) + endCharacters
if (hasWindowsNewlines) {
result = result.replace(/\n/g, '\r\n')
let result = JSON.stringify(over(json), null, indent) + endCharacters
if (newline === '\r\n') {
result = result.replace(/\n/g, newline)
}
return result
}
Expand Down
13 changes: 9 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
},
"dependencies": {
"detect-indent": "^6.0.0",
"detect-newline": "3.1.0",
"glob": "^7.1.6",
"sort-object-keys": "^1.1.2"
},
Expand Down
4 changes: 4 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ fs.readFile('./package.json', 'utf8', (error, contents) => {
sortPackageJson('{\r\n "foo": "bar"\r\n}\r\n'),
'{\r\n "foo": "bar"\r\n}\r\n',
)
assert.strictEqual(
sortPackageJson('{\r\n "foo": "bar"\n}\n'),
'{\n "foo": "bar"\n}\n',
)
})

// fields tests
Expand Down

0 comments on commit 425352e

Please sign in to comment.