diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 48a1c6a..aeeb24d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -19,6 +19,8 @@ jobs: node-version: ${{ matrix.node-version }} - name: Install dependencies run: yarn install --frozen-lockfile --ignore-engines --ignore-scripts + - name: build + run: yarn build - name: Run unit tests run: yarn test env: diff --git a/src/node.ts b/src/node.ts index 0c3b41d..dfe2c9f 100644 --- a/src/node.ts +++ b/src/node.ts @@ -1,6 +1,19 @@ import { isatty } from 'node:tty' -import { createColors } from './index' +import { + createColors as originalCreateColors, + isSupported as originalIsSupported, +} from './index' -export * from './index' +export { Colors, Formatter, getDefaultColors } from './index' -export default createColors(isatty(1)) +const isTTY = process.env.FORCE_TTY !== undefined || isatty(1) + +export function isSupportted() { + return originalIsSupported(isTTY) +} + +export function createColors() { + return originalCreateColors(isTTY) +} + +export default originalCreateColors(isTTY) diff --git a/tests/fixtures/child-process.mjs b/tests/fixtures/child-process.mjs new file mode 100644 index 0000000..165cd55 --- /dev/null +++ b/tests/fixtures/child-process.mjs @@ -0,0 +1,5 @@ +import c from '../../dist/node.js' + +console.log(c.green('Green')) +console.log(c.red('Red')) +console.log({ FORCE_TTY: process.env.FORCE_TTY }) diff --git a/tests/main.spec.ts b/tests/main.spec.ts index cc5a359..c9223e3 100644 --- a/tests/main.spec.ts +++ b/tests/main.spec.ts @@ -1,5 +1,8 @@ +import { fork } from 'node:child_process' import { createColors } from '../src/node' -import { assert, test } from 'vitest' +import { assert, expect, test } from 'vitest' +import { fileURLToPath } from 'node:url' +import { resolve } from 'node:path' const FMT = { reset: ['\x1b[0m', '\x1b[0m'], @@ -155,4 +158,46 @@ test('no maximum call stack error', () => { delete process.env.GITHUB_ACTIONS assert.isTrue(pc.isColorSupported) assert.exists(pc.blue(pc.blue('x').repeat(10000))) + delete process.env.FORCE_COLOR +}) + +test('non-TTY does not enable colors', async () => { + const proc = fork(resolve(__dirname, 'fixtures/child-process.mjs'), { + stdio: 'pipe', + }) + + let data = '' + proc.stdout!.on('data', (msg) => { + data += msg + }) + + await new Promise((r) => proc.on('exit', r)) + + expect(data).toMatchInlineSnapshot(` + "Green + Red + { FORCE_TTY: undefined } + " + `) +}) + +test('FORCE_TTY enables colors', async () => { + const proc = fork(resolve(__dirname, 'fixtures/child-process.mjs'), { + stdio: 'pipe', + env: { FORCE_TTY: 'true' }, + }) + + let data = '' + proc.stdout!.on('data', (msg) => { + data += msg + }) + + await new Promise((r) => proc.on('exit', r)) + + expect(data).toMatchInlineSnapshot(` + "Green + Red + { FORCE_TTY: 'true' } + " + `) })