diff --git a/index.js b/index.js index f053b51..41c5e07 100644 --- a/index.js +++ b/index.js @@ -8,15 +8,23 @@ let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { - forceColor = false; + forceColor = 0; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { - forceColor = true; + forceColor = 1; } if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; + if (env.FORCE_COLOR === true || env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === false || env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? + 1 : + Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } } function translateLevel(level) { @@ -33,7 +41,7 @@ function translateLevel(level) { } function supportsColor(stream) { - if (forceColor === false) { + if (forceColor === 0) { return 0; } @@ -47,11 +55,11 @@ function supportsColor(stream) { return 2; } - if (stream && !stream.isTTY && forceColor !== true) { + if (stream && !stream.isTTY && forceColor === undefined) { return 0; } - const min = forceColor ? 1 : 0; + const min = forceColor || 0; if (env.TERM === 'dumb') { return min; diff --git a/test.js b/test.js index f3d31b4..bbede42 100644 --- a/test.js +++ b/test.js @@ -325,6 +325,54 @@ test('return level 2 when FORCE_COLOR is set when not TTY in xterm256', t => { t.is(result.stdout.level, 2); }); +test('supports setting a color level using FORCE_COLOR', t => { + let result; + process.env.FORCE_COLOR = '1'; + result = importFresh('.'); + t.truthy(result.stdout); + t.is(result.stdout.level, 1); + + process.env.FORCE_COLOR = '2'; + result = importFresh('.'); + t.truthy(result.stdout); + t.is(result.stdout.level, 2); + + process.env.FORCE_COLOR = '3'; + result = importFresh('.'); + t.truthy(result.stdout); + t.is(result.stdout.level, 3); + + process.env.FORCE_COLOR = '0'; + result = importFresh('.'); + t.false(result.stdout); +}); + +test('FORCE_COLOR maxes out at a value of 3', t => { + process.env.FORCE_COLOR = '4'; + const result = importFresh('.'); + t.truthy(result.stdout); + t.is(result.stdout.level, 3); +}); + +test('FORCE_COLOR works when set via command line (all values are strings)', t => { + let result; + process.env.FORCE_COLOR = 'true'; + result = importFresh('.'); + t.truthy(result.stdout); + t.is(result.stdout.level, 1); + + process.stdout.isTTY = false; + process.env.FORCE_COLOR = 'true'; + process.env.TERM = 'xterm-256color'; + result = importFresh('.'); + t.truthy(result.stdout); + t.is(result.stdout.level, 2); + + process.env.FORCE_COLOR = 'false'; + result = importFresh('.'); + t.false(result.stdout); +}); + test('return false when `TERM` is set to dumb', t => { process.env.TERM = 'dumb'; const result = importFresh('.');