Skip to content

Commit

Permalink
Ensure any trailing whitespace in package.json is preserved.
Browse files Browse the repository at this point in the history
When testing the new `--write` functionality I noticed that my
`package.json` had changed trailing whitespace as well as the
`ember-source` URL. That was annoying.
  • Loading branch information
rwjblue committed May 16, 2019
1 parent 7109a8f commit d661a2c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
7 changes: 7 additions & 0 deletions bin/ember-source-channel-url
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const fs = require('fs');
const getChannelURL = require('../src');
const channel = process.argv[2];
const shouldUpdatePackage = process.argv.includes('-w') || process.argv.includes('--write');
const DETECT_TRAILING_WHITESPACE = /\s+$/;

function printUsage() {
console.log(`
Expand Down Expand Up @@ -55,6 +56,7 @@ if (['release', 'beta', 'canary'].indexOf(channel) === -1) {
}

let contents = fs.readFileSync('package.json', { encoding: 'utf8' });
let trailingWhitespace = DETECT_TRAILING_WHITESPACE.exec(contents);
let pkg = JSON.parse(contents);

let dependencyType = ['dependencies', 'devDependencies'].find(
Expand All @@ -65,6 +67,11 @@ if (['release', 'beta', 'canary'].indexOf(channel) === -1) {
pkg[dependencyType]['ember-source'] = url;

let updatedContents = JSON.stringify(pkg, null, 2);

if (trailingWhitespace) {
updatedContents += trailingWhitespace[0];
}

fs.writeFileSync('package.json', updatedContents, { encoding: 'utf8' });
} else {
console.log(
Expand Down
16 changes: 16 additions & 0 deletions tests/index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,22 @@ QUnit.module('ember-source-channel-url', function(hooks) {
});
});

QUnit.test('preserves line ending when updating package.json', function(assert) {
fs.writeFileSync(
'package.json',
JSON.stringify({ dependencies: { 'ember-source': '^3.10.0' } }, null, 2) + '\n',
{ encoding: 'utf8' }
);

return execa(EXECUTABLE_PATH, ['canary', '--write']).then(results => {
assert.ok(results.stdout.includes(this.expectedURL), 'URL is present in stdout');

let expected =
JSON.stringify({ dependencies: { 'ember-source': this.expectedURL } }, null, 2) + '\n';
assert.deepEqual(fs.readFileSync('package.json', { encoding: 'utf8' }), expected);
});
});

QUnit.test('fails when package.json is missing', function(assert) {
return execa(EXECUTABLE_PATH, ['canary', '--write']).catch(results => {
assert.ok(results.stdout.includes(this.expectedURL), 'URL is present in stdout');
Expand Down

0 comments on commit d661a2c

Please sign in to comment.