Skip to content

Commit 89d5c88

Browse files
authored
Fix NO_COLOR handling in CLI prompts and wizard (#8933)
1 parent ebe487f commit 89d5c88

8 files changed

Lines changed: 287 additions & 190 deletions

File tree

‎.changeset/cli-prompt-no-color.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Respect `NO_COLOR` in CLI prompts and the command wizard, suppressing color and style escapes while preserving cursor and redraw controls.

‎packages/effect/src/cli/CliOutput.ts‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as Layer from "../Layer.ts"
1616
import * as Option from "../Option.ts"
1717
import type * as CliError from "./CliError.ts"
1818
import type { HelpDoc } from "./HelpDoc.ts"
19+
import * as Ansi from "./internal/ansi.ts"
1920

2021
/**
2122
* Defines the service interface for formatting CLI output including help, errors, and version info.
@@ -306,17 +307,7 @@ const escapeControlCharacters = (text: string): string =>
306307
* @since 4.0.0
307308
*/
308309
export const defaultFormatter = (options?: { colors?: boolean }): Formatter => {
309-
const globalProcess = (globalThis as any).process
310-
const hasProcess = typeof globalProcess === "object" && globalProcess !== null
311-
312-
const useColor = options?.colors !== undefined
313-
? options.colors
314-
// Auto-detect based on environment
315-
: (hasProcess &&
316-
typeof globalProcess.stdout === "object" &&
317-
globalProcess.stdout !== null &&
318-
globalProcess.stdout.isTTY === true &&
319-
!globalProcess.env?.NO_COLOR)
310+
const useColor = options?.colors ?? Ansi.detectColors()
320311

321312
// Color palette using ANSI escape codes
322313
const colors = useColor

‎packages/effect/src/cli/Command.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1934,14 +1934,15 @@ export const runWith = <const Name extends string, Input, E, R, ContextInput>(
19341934
if (!hasEntry) continue
19351935
const [, value] = yield* flag.flag.parse(emptyArgs)
19361936
if (flag === GlobalFlag.Wizard) {
1937+
const { colors } = yield* Prompt.Theme
19371938
return yield* Effect.gen(function*() {
1938-
yield* Console.log(Wizard.renderIntroduction(command.name, config.version, command.description))
1939+
yield* Console.log(Wizard.renderIntroduction(command.name, config.version, command.description, colors))
19391940
const prefix = [
19401941
command.name,
19411942
...args.filter((arg) => arg !== "--wizard" && !arg.startsWith("--wizard="))
19421943
]
19431944
const wizardResult = yield* Wizard.run(command, { commandPath, prefix })
1944-
yield* Console.log(Wizard.renderCompletion(wizardResult.displayArgs))
1945+
yield* Console.log(Wizard.renderCompletion(wizardResult.displayArgs, colors))
19451946
const shouldRun = yield* Prompt.run(Prompt.Toggle({
19461947
message: "Run this command?",
19471948
initial: true,
@@ -1953,7 +1954,7 @@ export const runWith = <const Name extends string, Input, E, R, ContextInput>(
19531954
yield* runWith(command, { ...config, renderErrors: false })(wizardResult.args.slice(1))
19541955
}
19551956
}).pipe(
1956-
Effect.catchTag("QuitError", () => Console.log(Wizard.renderQuit()))
1957+
Effect.catchTag("QuitError", () => Console.log(Wizard.renderQuit(colors)))
19571958
)
19581959
}
19591960
yield* flag.run(value, handlerCtx)

‎packages/effect/src/cli/Prompt.ts‎

Lines changed: 154 additions & 145 deletions
Large diffs are not rendered by default.

‎packages/effect/src/cli/internal/ansi.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,32 @@ export const blackBright = `${ESC}90m`
105105
*/
106106
export const cyanBright = `${ESC}96m`
107107

108-
export const annotate = (text: string, ...styles: Array<string | Array<string>>) => {
109-
const flat = styles.flat()
110-
return `${flat.join("")}${text}${reset}`
108+
/**
109+
* Wraps `text` in the given styles followed by a reset. When `colors` is
110+
* `false` the text is returned unchanged, so callers gate color and style
111+
* escapes in one place while cursor and erase controls stay untouched.
112+
*
113+
* @internal
114+
*/
115+
export const annotate = (colors: boolean, text: string, ...styles: Array<string | Array<string>>): string => {
116+
if (!colors) return text
117+
return `${styles.flat().join("")}${text}${reset}`
118+
}
119+
120+
/**
121+
* Detects whether CLI output should use color and style escapes: stdout must
122+
* be a TTY and `NO_COLOR` must be unset or empty.
123+
*
124+
* @internal
125+
*/
126+
export const detectColors = (): boolean => {
127+
const globalProcess = (globalThis as any).process
128+
return typeof globalProcess === "object" &&
129+
globalProcess !== null &&
130+
typeof globalProcess.stdout === "object" &&
131+
globalProcess.stdout !== null &&
132+
globalProcess.stdout.isTTY === true &&
133+
!globalProcess.env?.NO_COLOR
111134
}
112135

113136
export const combine = (...styles: Array<string>): Array<string> => styles

‎packages/effect/src/cli/internal/wizard.ts‎

Lines changed: 34 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@ export const run: (
3434
const commandPath = options?.commandPath ?? [command.name]
3535
const selected = getCommandAtPath(command, commandPath)
3636
const commandLine = (options?.prefix ?? commandPath).map((value) => commandLineArg(value))
37-
yield* logCurrentCommand(commandLine)
38-
yield* promptCommand(selected, commandLine, selected === command ? "ROOT" : selected.name)
37+
const { colors } = yield* Prompt.Theme
38+
yield* logCurrentCommand(commandLine, colors)
39+
yield* promptCommand(selected, commandLine, selected === command ? "ROOT" : selected.name, colors)
3940
return {
4041
args: commandLine.map((arg) => arg.value),
4142
displayArgs: commandLine.map((arg) => arg.displayValue)
@@ -63,30 +64,31 @@ const getCommandAtPath = (
6364
const promptCommand: (
6465
command: Command.Command.Any,
6566
commandLine: Array<CommandLineArg>,
66-
sectionName: string
67+
sectionName: string,
68+
colors: boolean
6769
) => Effect.Effect<void, CliError.CliError | Terminal.QuitError, Command.Environment> = Effect.fnUntraced(
68-
function*(command, commandLine, sectionName) {
70+
function*(command, commandLine, sectionName, colors) {
6971
const impl = toImpl(command)
7072
const visibleSubcommands = command.subcommands.flatMap((group) => group.commands.filter((child) => !child.unlisted))
7173
const config = visibleSubcommands.length === 0 ? impl.config : impl.contextConfig
7274

7375
if (config.flags.length > 0) {
74-
yield* Console.log(renderSection(sectionName, "FLAGS"))
76+
yield* Console.log(renderSection(sectionName, "FLAGS", colors))
7577
for (const param of config.flags) {
7678
commandLine.push(...yield* promptParam(param))
7779
}
7880
if (config.arguments.length > 0 || visibleSubcommands.length > 0) {
79-
yield* logCurrentCommand(commandLine)
81+
yield* logCurrentCommand(commandLine, colors)
8082
}
8183
}
8284

8385
if (config.arguments.length > 0) {
84-
yield* Console.log(renderSection(sectionName, "ARGUMENTS"))
86+
yield* Console.log(renderSection(sectionName, "ARGUMENTS", colors))
8587
for (const param of config.arguments) {
8688
commandLine.push(...yield* promptParam(param))
8789
}
8890
if (visibleSubcommands.length > 0) {
89-
yield* logCurrentCommand(commandLine)
91+
yield* logCurrentCommand(commandLine, colors)
9092
}
9193
}
9294

@@ -109,9 +111,9 @@ const promptCommand: (
109111
yield* Console.log()
110112
commandLine.push(commandLineArg(child.name))
111113
if (hasWizardSteps(child)) {
112-
yield* logCurrentCommand(commandLine)
114+
yield* logCurrentCommand(commandLine, colors)
113115
}
114-
yield* promptCommand(child, commandLine, child.name)
116+
yield* promptCommand(child, commandLine, child.name, colors)
115117
}
116118
)
117119

@@ -244,41 +246,47 @@ const humanize = (name: string): string => {
244246
return [words[0][0].toUpperCase() + words[0].slice(1), ...words.slice(1)].join(" ")
245247
}
246248

247-
const logCurrentCommand = (commandLine: ReadonlyArray<CommandLineArg>): Effect.Effect<void> =>
248-
Console.log(renderCommandBlock("Current command", commandLine.map((arg) => arg.displayValue), Ansi.magenta))
249+
const logCurrentCommand = (commandLine: ReadonlyArray<CommandLineArg>, colors: boolean): Effect.Effect<void> =>
250+
Console.log(renderCommandBlock("Current command", commandLine.map((arg) => arg.displayValue), colors, Ansi.magenta))
249251

250-
const renderSection = (commandName: string, section: string): string =>
251-
`${Ansi.annotate(commandName.toUpperCase(), Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate("·", Ansi.blackBright)} ${
252-
Ansi.annotate(section, Ansi.bold, Ansi.white)
253-
}`
252+
const renderSection = (commandName: string, section: string, colors: boolean): string =>
253+
`${Ansi.annotate(colors, commandName.toUpperCase(), Ansi.bold, Ansi.cyanBright)} ${
254+
Ansi.annotate(colors, "·", Ansi.blackBright)
255+
} ${Ansi.annotate(colors, section, Ansi.bold, Ansi.white)}`
254256

255-
export const renderIntroduction = (name: string, version: string, summary: string | undefined): string => {
256-
const title = `${Ansi.annotate(name, Ansi.bold, Ansi.cyanBright)} ${Ansi.annotate(`v${version}`, Ansi.white)} ${
257-
Ansi.annotate("· Command wizard", Ansi.bold, Ansi.white)
258-
}`
257+
export const renderIntroduction = (
258+
name: string,
259+
version: string,
260+
summary: string | undefined,
261+
colors: boolean
262+
): string => {
263+
const title = `${Ansi.annotate(colors, name, Ansi.bold, Ansi.cyanBright)} ${
264+
Ansi.annotate(colors, `v${version}`, Ansi.white)
265+
} ${Ansi.annotate(colors, "· Command wizard", Ansi.bold, Ansi.white)}`
259266
return [
260267
title,
261268
...(summary === undefined || summary.length === 0 ? [] : [summary]),
262-
Ansi.annotate("Build a command interactively. Press Ctrl+C to cancel.", Ansi.blackBright),
269+
Ansi.annotate(colors, "Build a command interactively. Press Ctrl+C to cancel.", Ansi.blackBright),
263270
""
264271
].join("\n")
265272
}
266273

267-
export const renderCompletion = (commandLine: ReadonlyArray<string>): string =>
268-
renderCommandBlock("Command ready", commandLine, Ansi.cyanBright, Ansi.green)
274+
export const renderCompletion = (commandLine: ReadonlyArray<string>, colors: boolean): string =>
275+
renderCommandBlock("Command ready", commandLine, colors, Ansi.cyanBright, Ansi.green)
269276

270-
export const renderQuit = (): string => `\n${Ansi.annotate("Wizard cancelled.", Ansi.red)}`
277+
export const renderQuit = (colors: boolean): string => `\n${Ansi.annotate(colors, "Wizard cancelled.", Ansi.red)}`
271278

272279
const renderCommandBlock = (
273280
label: string,
274281
commandLine: ReadonlyArray<string>,
282+
colors: boolean,
275283
commandColor: string,
276284
labelColor: string = Ansi.white
277285
): string => {
278286
const lines = wrapCommand(commandLine)
279287
return [
280-
Ansi.annotate(label, Ansi.bold, labelColor),
281-
...lines.map((line) => Ansi.annotate(line, commandColor)),
288+
Ansi.annotate(colors, label, Ansi.bold, labelColor),
289+
...lines.map((line) => Ansi.annotate(colors, line, commandColor)),
282290
""
283291
].join("\n")
284292
}

‎packages/effect/test/cli/Command.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { assert, describe, expect, it } from "@effect/vitest"
22
import { Context, Effect, Fiber, FileSystem, Layer, Option, Path, Redacted, Runtime, Stdio } from "effect"
3-
import { Argument, CliConfig, CliError, CliOutput, Command, Flag, GlobalFlag } from "effect/cli"
3+
import { Argument, CliConfig, CliError, CliOutput, Command, Flag, GlobalFlag, Prompt } from "effect/cli"
44
import { toImpl } from "effect/cli/internal/command"
55
import { ChildProcessSpawner } from "effect/process"
66
import { TestConsole } from "effect/testing"
@@ -47,6 +47,21 @@ const TestLayerWithoutFormatter = Layer.mergeAll(
4747
)
4848

4949
describe("Command", () => {
50+
it.effect("omits styles from wizard headings and command blocks when colors are disabled", () =>
51+
Effect.gen(function*() {
52+
const command = Command.make("greet", { name: Flag.String("name") }, () => Effect.void)
53+
54+
const fiber = yield* Command.runWith(command, { version: "1.0.0" })(["--wizard"]).pipe(Effect.forkChild)
55+
yield* MockTerminal.inputText("Alice")
56+
yield* MockTerminal.inputKey("enter")
57+
yield* MockTerminal.inputKey("enter")
58+
yield* Fiber.join(fiber)
59+
60+
const logs = (yield* TestConsole.logLines).join("\n")
61+
assert.include(logs, "$ greet --name Alice")
62+
assert.notMatch(logs, new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`))
63+
}).pipe(Effect.provide([TestLayer, Layer.succeed(Prompt.Theme, Prompt.makeTheme({ colors: false }))])))
64+
5065
describe("annotations", () => {
5166
it.effect("should expose annotations in help docs", () =>
5267
Effect.gen(function*() {

‎packages/effect/test/cli/Prompt.test.ts‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,22 @@
11
import { assert, describe, it } from "@effect/vitest"
22
import { Data, DateTime, Deferred, Effect, Fiber, FileSystem, Layer, Match, Path, Queue, Redacted } from "effect"
33
import { Prompt } from "effect/cli"
4+
import { afterEach, vi } from "vitest"
45
import * as MockTerminal from "./services/MockTerminal.ts"
56

67
const FileSystemLayer = FileSystem.layerNoop({})
78
const PathLayer = Path.layer
89
const TerminalLayer = MockTerminal.layer
910

11+
// Styling assertions assume a color-capable terminal, independent of the test
12+
// process environment.
13+
const ThemeLayer = Layer.succeed(Prompt.Theme, Prompt.makeTheme({ colors: true }))
14+
1015
const TestLayer = Layer.mergeAll(
1116
FileSystemLayer,
1217
PathLayer,
13-
TerminalLayer
18+
TerminalLayer,
19+
ThemeLayer
1420
)
1521
const Action = Data.taggedEnum<Prompt.ActionDefinition>()
1622

@@ -49,6 +55,44 @@ const toRawFrames = (lines: ReadonlyArray<unknown>) =>
4955

5056
const findFrame = (frames: ReadonlyArray<string>, text: string) => frames.find((frame) => frame.includes(text))
5157

58+
describe("Prompt colors", () => {
59+
describe("makeTheme detection", { concurrent: false }, () => {
60+
const isTTY = Object.getOwnPropertyDescriptor(process.stdout, "isTTY")
61+
62+
afterEach(() => {
63+
vi.unstubAllEnvs()
64+
if (isTTY === undefined) {
65+
delete (process.stdout as { isTTY?: boolean }).isTTY
66+
} else {
67+
Object.defineProperty(process.stdout, "isTTY", isTTY)
68+
}
69+
})
70+
71+
it("disables colors when NO_COLOR is set on a TTY", () => {
72+
Object.defineProperty(process.stdout, "isTTY", { value: true, configurable: true })
73+
vi.stubEnv("NO_COLOR", "1")
74+
75+
assert.isFalse(Prompt.makeTheme().colors)
76+
})
77+
})
78+
79+
it.effect("omits styles when the context theme disables colors", () =>
80+
Effect.gen(function*() {
81+
yield* MockTerminal.inputKey("enter")
82+
yield* Prompt.run(Prompt.Select({
83+
message: "Choose a color",
84+
choices: [{ title: "Blue", value: "blue" }]
85+
}))
86+
87+
const output = (yield* MockTerminal.displayLines).join("\n")
88+
assert.include(output, "Choose a color")
89+
assert.notMatch(output, new RegExp(`${escape}\\[[0-9;]*m`))
90+
}).pipe(
91+
Effect.provideService(Prompt.Theme, Prompt.makeTheme({ colors: false })),
92+
Effect.provide(TestLayer)
93+
))
94+
})
95+
5296
describe("Prompt.Date", () => {
5397
it.effect("renders two-digit years, teen ordinals, and noon meridiem correctly", () =>
5498
Effect.gen(function*() {
@@ -252,6 +296,7 @@ describe("Prompt.String", () => {
252296
Effect.provideService(
253297
Prompt.Theme,
254298
Prompt.makeTheme({
299+
colors: true,
255300
primaryColor: `${escape}[31m`,
256301
mutedColor: `${escape}[34m`,
257302
successColor: `${escape}[33m`,

0 commit comments

Comments
 (0)