Skip to content

Commit

Permalink
feat: Retain Windows newlines after sorting package.json strings (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
Shingyx authored and keithamus committed Mar 3, 2019
1 parent 262ef2d commit 7a953c7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
14 changes: 11 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ const defaultNpmScripts = [
function sortPackageJson(packageJson, options = {}) {
const determinedSortOrder = options.sortOrder || sortOrder;
let wasString = false;
let hasWindowsNewlines = false;
let endCharacters = '';
let indentLevel = 2;
if (typeof packageJson === 'string') {
Expand All @@ -91,6 +92,8 @@ function sortPackageJson(packageJson, options = {}) {
if (packageJson.substr(-1) === '\n') {
endCharacters = '\n';
}
const newlineMatch = packageJson.match(/(\r?\n)/);
hasWindowsNewlines = (newlineMatch && newlineMatch[0]) === '\r\n';
packageJson = JSON.parse(packageJson);
}

Expand Down Expand Up @@ -185,9 +188,14 @@ function sortPackageJson(packageJson, options = {}) {
sortSubKey('private');
sortSubKey('publishConfig');
packageJson = sortObjectKeys(packageJson, determinedSortOrder);
return wasString
? JSON.stringify(packageJson, null, indentLevel) + endCharacters
: packageJson;
if (wasString) {
let result = JSON.stringify(packageJson, null, indentLevel) + endCharacters;
if (hasWindowsNewlines) {
result = result.replace(/\n/g, '\r\n');
}
return result;
}
return packageJson;
}
module.exports = sortPackageJson;
module.exports.sortPackageJson = sortPackageJson;
Expand Down
6 changes: 6 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ fs.readFile('./package.json', 'utf8', (error, contents) => {
['engines', 'name']
);

assert.equal(sortPackageJson('{}'), '{}');
assert.equal(sortPackageJson('{}\n'), '{}\n');
assert.equal(sortPackageJson('{}\r\n'), '{}\r\n');
assert.equal(sortPackageJson('{"foo":"bar"}\n'), '{"foo":"bar"}\n');

assert.equal(
Expand All @@ -105,5 +107,9 @@ fs.readFile('./package.json', 'utf8', (error, contents) => {
sortPackageJson('{\n "name": "foo",\n "version": "1.0.0"\n}'),
'{\n "name": "foo",\n "version": "1.0.0"\n}'
);
assert.equal(
sortPackageJson('{\r\n "foo": "bar"\r\n}\r\n'),
'{\r\n "foo": "bar"\r\n}\r\n'
);
});

0 comments on commit 7a953c7

Please sign in to comment.