Skip to content

Commit

Permalink
fix: better color support detection (#6556)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukekarrys authored Jun 15, 2023
1 parent cd1e6aa commit d980405
Show file tree
Hide file tree
Showing 12 changed files with 698 additions and 306 deletions.
1 change: 1 addition & 0 deletions DEPENDENCIES.md
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,7 @@ graph LR;
npm-->sigstore;
npm-->spawk;
npm-->ssri;
npm-->supports-color;
npm-->tap;
npm-->tar;
npm-->text-table;
Expand Down
16 changes: 13 additions & 3 deletions lib/commands/doctor.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,8 @@ class Doctor extends BaseCommand {

output (row) {
const t = new Table({
chars: { top: '',
chars: {
top: '',
'top-mid': '',
'top-left': '',
'top-right': '',
Expand All @@ -385,8 +386,17 @@ class Doctor extends BaseCommand {
'mid-mid': '',
right: '',
'right-mid': '',
middle: ' ' },
style: { 'padding-left': 0, 'padding-right': 0 },
middle: ' ',
},
style: {
'padding-left': 0,
'padding-right': 0,
// setting border here is not necessary visually since we've already
// zeroed out all the chars above, but without it cli-table3 will wrap
// some of the separator spaces with ansi codes which show up in
// snapshots.
border: 0,
},
colWidths: [this.#checkWidth, 6],
})
t.push(row)
Expand Down
17 changes: 12 additions & 5 deletions lib/npm.js
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,19 @@ class Npm {

await this.time('npm:load:configload', () => this.config.load())

const { Chalk, supportsColor, supportsColorStderr } = await import('chalk')
// get createSupportsColor from chalk directly if this lands
// https://github.com/chalk/chalk/pull/600
const [{ Chalk }, { createSupportsColor }] = await Promise.all([
import('chalk'),
import('supports-color'),
])
this.#noColorChalk = new Chalk({ level: 0 })
this.#chalk = this.color ? new Chalk({ level: supportsColor.level })
: this.#noColorChalk
this.#logChalk = this.logColor ? new Chalk({ level: supportsColorStderr.level })
: this.#noColorChalk
// we get the chalk level based on a null stream meaning chalk will only use
// what it knows about the environment to get color support since we already
// determined in our definitions that we want to show colors.
const level = Math.max(createSupportsColor(null).level, 1)
this.#chalk = this.color ? new Chalk({ level }) : this.#noColorChalk
this.#logChalk = this.logColor ? new Chalk({ level }) : this.#noColorChalk

// mkdir this separately since the logs dir can be set to
// a different location. if this fails, then we don't have
Expand Down
1 change: 1 addition & 0 deletions node_modules/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@
!/string-width
!/strip-ansi-cjs
!/strip-ansi
!/supports-color
!/tar
!/tar/node_modules/
/tar/node_modules/*
Expand Down
30 changes: 30 additions & 0 deletions node_modules/supports-color/browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/* eslint-env browser */

const level = (() => {
if (navigator.userAgentData) {
const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
if (brand?.version > 93) {
return 3;
}
}

if (/\b(Chrome|Chromium)\//.test(navigator.userAgent)) {
return 1;
}

return 0;
})();

const colorSupport = level !== 0 && {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};

const supportsColor = {
stdout: colorSupport,
stderr: colorSupport,
};

export default supportsColor;
182 changes: 182 additions & 0 deletions node_modules/supports-color/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import process from 'node:process';
import os from 'node:os';
import tty from 'node:tty';

// From: https://github.com/sindresorhus/has-flag/blob/main/index.js
/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--');
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}

const {env} = process;

let flagForceColor;
if (
hasFlag('no-color')
|| hasFlag('no-colors')
|| hasFlag('color=false')
|| hasFlag('color=never')
) {
flagForceColor = 0;
} else if (
hasFlag('color')
|| hasFlag('colors')
|| hasFlag('color=true')
|| hasFlag('color=always')
) {
flagForceColor = 1;
}

function envForceColor() {
if ('FORCE_COLOR' in env) {
if (env.FORCE_COLOR === 'true') {
return 1;
}

if (env.FORCE_COLOR === 'false') {
return 0;
}

return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
}
}

function translateLevel(level) {
if (level === 0) {
return false;
}

return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
}

function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {
const noFlagForceColor = envForceColor();
if (noFlagForceColor !== undefined) {
flagForceColor = noFlagForceColor;
}

const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;

if (forceColor === 0) {
return 0;
}

if (sniffFlags) {
if (hasFlag('color=16m')
|| hasFlag('color=full')
|| hasFlag('color=truecolor')) {
return 3;
}

if (hasFlag('color=256')) {
return 2;
}
}

// Check for Azure DevOps pipelines.
// Has to be above the `!streamIsTTY` check.
if ('TF_BUILD' in env && 'AGENT_NAME' in env) {
return 1;
}

if (haveStream && !streamIsTTY && forceColor === undefined) {
return 0;
}

const min = forceColor || 0;

if (env.TERM === 'dumb') {
return min;
}

if (process.platform === 'win32') {
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
const osRelease = os.release().split('.');
if (
Number(osRelease[0]) >= 10
&& Number(osRelease[2]) >= 10_586
) {
return Number(osRelease[2]) >= 14_931 ? 3 : 2;
}

return 1;
}

if ('CI' in env) {
if ('GITHUB_ACTIONS' in env) {
return 3;
}

if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}

return min;
}

if ('TEAMCITY_VERSION' in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}

if (env.COLORTERM === 'truecolor') {
return 3;
}

if (env.TERM === 'xterm-kitty') {
return 3;
}

if ('TERM_PROGRAM' in env) {
const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);

switch (env.TERM_PROGRAM) {
case 'iTerm.app': {
return version >= 3 ? 3 : 2;
}

case 'Apple_Terminal': {
return 2;
}
// No default
}
}

if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}

if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}

if ('COLORTERM' in env) {
return 1;
}

return min;
}

export function createSupportsColor(stream, options = {}) {
const level = _supportsColor(stream, {
streamIsTTY: stream && stream.isTTY,
...options,
});

return translateLevel(level);
}

const supportsColor = {
stdout: createSupportsColor({isTTY: tty.isatty(1)}),
stderr: createSupportsColor({isTTY: tty.isatty(2)}),
};

export default supportsColor;
9 changes: 9 additions & 0 deletions node_modules/supports-color/license
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
61 changes: 61 additions & 0 deletions node_modules/supports-color/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "supports-color",
"version": "9.3.1",
"description": "Detect whether a terminal supports color",
"license": "MIT",
"repository": "chalk/supports-color",
"funding": "https://github.com/chalk/supports-color?sponsor=1",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": {
"node": "./index.js",
"default": "./browser.js"
},
"engines": {
"node": ">=12"
},
"scripts": {
"//test": "xo && ava && tsd",
"test": "xo && tsd"
},
"files": [
"index.js",
"index.d.ts",
"browser.js",
"browser.d.ts"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"ansi",
"styles",
"tty",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"support",
"supports",
"capability",
"detect",
"truecolor",
"16m"
],
"devDependencies": {
"@types/node": "^16.11.7",
"ava": "^3.15.0",
"import-fresh": "^3.3.0",
"tsd": "^0.18.0",
"typescript": "^4.4.3",
"xo": "^0.49.0"
}
}
Loading

0 comments on commit d980405

Please sign in to comment.