Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow setting support level with FORCE_COLOR environment variable #85

Merged
merged 6 commits into from Dec 21, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion index.js
Expand Up @@ -15,8 +15,18 @@ if (hasFlag('no-color') ||
hasFlag('color=always')) {
forceColor = true;
}
let forceLevel;
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 = true;
} else if (env.FORCE_COLOR === false || env.FORCE_COLOR === 'false') {
forceColor = false;
} else {
forceLevel = env.FORCE_COLOR.length === 0 ?
1 :
parseInt(env.FORCE_COLOR, 10);
forceColor = forceLevel !== 0;
}
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
}

function translateLevel(level) {
Expand Down Expand Up @@ -47,6 +57,10 @@ function supportsColor(stream) {
return 2;
}

if (forceLevel !== undefined) {
return forceLevel;
}

if (stream && !stream.isTTY && forceColor !== true) {
return 0;
}
Expand Down
32 changes: 32 additions & 0 deletions test.js
Expand Up @@ -317,3 +317,35 @@ test('return level 2 when FORCE_COLOR is set when not TTY in xterm256', t => {
t.truthy(result.stdout);
t.is(result.stdout.level, 2);
});

test('supports setting a color value using FORCE_COLOR', t => {
let result;
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);
});
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved

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);
});