Skip to content

Commit

Permalink
Rework color detection (#87)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
alexeyraspopov authored Oct 16, 2024
1 parent ef5553b commit 5b01210
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
1 change: 1 addition & 0 deletions .github/workflows/testing.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ jobs:
strategy:
matrix:
node-version:
- 20
- 18
- 16
- 14
Expand Down
15 changes: 8 additions & 7 deletions picocolors.js
Original file line number Diff line number Diff line change
@@ -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) =>
Expand Down
17 changes: 15 additions & 2 deletions tests/environments.js
Original file line number Diff line number Diff line change
Expand Up @@ -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" } })
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 5b01210

Please # to comment.