From 5b01210390006229a9c9f4622234d43124b9daeb Mon Sep 17 00:00:00 2001 From: Oleksii Date: Wed, 16 Oct 2024 14:01:22 -0400 Subject: [PATCH] Rework color detection (#87) * add node v20 to the testing matrix * use process.stdout.isTTY instead of require * properly test env variables * adding empty NO_COLOR test * github actions again? * remove unnecessary alias * make nonempty testing easier since env variables always string|undefined --- .github/workflows/testing.yaml | 1 + picocolors.js | 15 ++++++++------- tests/environments.js | 17 +++++++++++++++-- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/.github/workflows/testing.yaml b/.github/workflows/testing.yaml index 32634df..6179ed8 100644 --- a/.github/workflows/testing.yaml +++ b/.github/workflows/testing.yaml @@ -13,6 +13,7 @@ jobs: strategy: matrix: node-version: + - 20 - 18 - 16 - 14 diff --git a/picocolors.js b/picocolors.js index d9ede1e..2dc32be 100644 --- a/picocolors.js +++ b/picocolors.js @@ -1,12 +1,13 @@ -let argv = process.argv || [], - env = process.env +let p = process || {}, + argv = p.argv || [], + env = p.env || {} let isColorSupported = - !("NO_COLOR" in env || argv.includes("--no-color")) && - ("FORCE_COLOR" in env || + !(!!env.NO_COLOR || argv.includes("--no-color")) && + (!!env.FORCE_COLOR || argv.includes("--color") || - process.platform === "win32" || - (require != null && require("tty").isatty(1) && env.TERM !== "dumb") || - "CI" in env) + p.platform === "win32" || + ((p.stdout || {}).isTTY && env.TERM !== "dumb") || + !!env.CI) let formatter = (open, close, replace = open) => diff --git a/tests/environments.js b/tests/environments.js index 1a9fa3a..8ac23ca 100644 --- a/tests/environments.js +++ b/tests/environments.js @@ -3,6 +3,7 @@ let fs = require("fs") let pc = require("../picocolors.js") let assert = require("assert") let source = fs.readFileSync(__dirname + "/../picocolors.js", "utf-8") +let CI = process.env.CI test("ci server", () => { let pc = initModuleEnv({ env: { TERM: "dumb", CI: "1" } }) @@ -22,6 +23,12 @@ test("env NO_COLOR", () => { assert.equal(pc.red("text"), pc.createColors(false).red("text")) }) +test("env NO_COLOR empty", () => { + let pc = initModuleEnv({ env: { NO_COLOR: "", CI } }) + assert.equal(pc.isColorSupported, true) + assert.equal(pc.red("text"), pc.createColors(true).red("text")) +}) + test("env FORCE_COLOR", () => { let pc = initModuleEnv({ env: { TERM: "dumb", FORCE_COLOR: "1" } }) assert.equal(pc.isColorSupported, true) @@ -62,8 +69,14 @@ function test(name, fn) { } } -function initModuleEnv({ env, argv = [], platform = "darwin", require = global.require }) { - let process = { env, argv, platform } +function initModuleEnv({ + env, + argv = [], + platform = "darwin", + require = global.require, + stdout = process.stdout, +}) { + let process = { env, argv, platform, stdout } let context = vm.createContext({ require, process, module: { exports: {} } }) let script = new vm.Script(source) script.runInContext(context)