Skip to content

Commit 425352e

Browse files
fiskerkeithamus
authored andcommittedDec 10, 2019
feat: new eol detection (#96)
1 parent a91a766 commit 425352e

File tree

4 files changed

+20
-10
lines changed

4 files changed

+20
-10
lines changed
 

‎index.js

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env node
22
const _sortObjectKeys = require('sort-object-keys')
33
const detectIndent = require('detect-indent')
4+
const detectNewline = require('detect-newline').graceful
45
const glob = require('glob')
56
const sortObjectKeys = comp => x => _sortObjectKeys(x, comp)
67

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

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

128-
let result = JSON.stringify(over(json), null, indentLevel) + endCharacters
129-
if (hasWindowsNewlines) {
130-
result = result.replace(/\n/g, '\r\n')
128+
let result = JSON.stringify(over(json), null, indent) + endCharacters
129+
if (newline === '\r\n') {
130+
result = result.replace(/\n/g, newline)
131131
}
132132
return result
133133
}

‎package-lock.json

+9-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
},
5151
"dependencies": {
5252
"detect-indent": "^6.0.0",
53+
"detect-newline": "3.1.0",
5354
"glob": "^7.1.6",
5455
"sort-object-keys": "^1.1.2"
5556
},

‎test.js

+4
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ fs.readFile('./package.json', 'utf8', (error, contents) => {
130130
sortPackageJson('{\r\n "foo": "bar"\r\n}\r\n'),
131131
'{\r\n "foo": "bar"\r\n}\r\n',
132132
)
133+
assert.strictEqual(
134+
sortPackageJson('{\r\n "foo": "bar"\n}\n'),
135+
'{\n "foo": "bar"\n}\n',
136+
)
133137
})
134138

135139
// fields tests

0 commit comments

Comments
 (0)
Please sign in to comment.