Skip to content

Commit

Permalink
Fix CLI's --space option parsing (#342)
Browse files Browse the repository at this point in the history
  • Loading branch information
noahbrenner authored and sindresorhus committed Jul 28, 2018
1 parent 98dee9a commit f76c901
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
18 changes: 18 additions & 0 deletions main.js
Expand Up @@ -114,6 +114,24 @@ updateNotifier({pkg: cli.pkg}).notify();

const {input, flags: opts} = cli;

// Make data types for `opts.space` match those of the API
// Check for string type because `xo --no-space` sets `opts.space` to `false`
if (typeof opts.space === 'string') {
if (/^\d+$/.test(opts.space)) {
opts.space = parseInt(opts.space, 10);
} else if (opts.space === 'true') {
opts.space = true;
} else if (opts.space === 'false') {
opts.space = false;
} else {
if (opts.space !== '') {
// Assume `opts.space` was set to a filename when run as `xo --space file.js`
input.push(opts.space);
}
opts.space = true;
}
}

const log = report => {
const reporter = opts.reporter ? xo.getFormatter(opts.reporter) : formatterPretty;

Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/space/one-space.js
@@ -0,0 +1,3 @@
console.log([
1
]);
3 changes: 3 additions & 0 deletions test/fixtures/space/two-spaces.js
@@ -0,0 +1,3 @@
console.log([
1
]);
35 changes: 35 additions & 0 deletions test/main.js
Expand Up @@ -115,3 +115,38 @@ test('cli option takes precedence over config', async t => {
// i.e make sure absent cli flags are not parsed as `false`
await t.throws(main(['--stdin'], {input}));
});

test('space option with number value', async t => {
const cwd = path.join(__dirname, 'fixtures/space');
const {stdout} = await t.throws(main(['--space=4', 'one-space.js'], {cwd}));
t.true(stdout.includes('Expected indentation of 4 spaces'));
});

test('space option as boolean', async t => {
const cwd = path.join(__dirname, 'fixtures/space');
const {stdout} = await t.throws(main(['--space'], {cwd}));
t.true(stdout.includes('Expected indentation of 2 spaces'));
});

test('space option as boolean with filename', async t => {
const cwd = path.join(__dirname, 'fixtures/space');
const {stdout} = await main(['--reporter=json', '--space', 'two-spaces.js'], {
cwd,
reject: false
});
const reports = JSON.parse(stdout);

// Only the specified file was checked (filename was not the value of `space`)
t.is(reports.length, 1);

// The default space value of 2 was expected
t.is(reports[0].errorCount, 0);
});

test('space option with boolean strings', async t => {
const cwd = path.join(__dirname, 'fixtures/space');
const trueResult = await t.throws(main(['--space=true'], {cwd}));
const falseResult = await t.throws(main(['--space=false'], {cwd}));
t.true(trueResult.stdout.includes('Expected indentation of 2 spaces'));
t.true(falseResult.stdout.includes('Expected indentation of 1 tab'));
});

0 comments on commit f76c901

Please sign in to comment.