diff --git a/src/cli.nim b/src/cli.nim index 9493ba9d..78da9cca 100644 --- a/src/cli.nim +++ b/src/cli.nim @@ -185,8 +185,21 @@ proc showVersion = echo &"{configletVersion}" quit(0) +proc shouldUseColor(f: File): bool = + ## Returns true if we should write to `f` with color. + existsEnv("CI") or + (isatty(f) and not existsEnv("NO_COLOR") and getEnv("TERM") != "dumb") + +let + colorStdout* = shouldUseColor(stdout) + colorStderr* = shouldUseColor(stderr) + proc showError*(s: string) = - stderr.styledWrite(fgRed, "Error: ") + const errorPrefix = "Error: " + if colorStderr: + stderr.styledWrite(fgRed, errorPrefix) + else: + stderr.write(errorPrefix) stderr.write(s) stderr.write("\n\n") showHelp(exitCode = 1) diff --git a/src/helpers.nim b/src/helpers.nim index abe924c6..606c75db 100644 --- a/src/helpers.nim +++ b/src/helpers.nim @@ -1,4 +1,5 @@ import std/[algorithm, os, terminal] +import "."/cli template withDir*(dir: string; body: untyped): untyped = ## Changes the current directory to `dir` temporarily. @@ -21,6 +22,10 @@ proc setFalseAndPrint*(b: var bool; description: string; details: string) = ## Sets `b` to `false` and writes a message to stdout containing `description` ## and `details`. b = false - stdout.styledWriteLine(fgRed, description & ":") + let descriptionPrefix = description & ":" + if colorStdout: + stdout.styledWriteLine(fgRed, descriptionPrefix) + else: + stdout.writeLine(descriptionPrefix) stdout.writeLine(details) stdout.write "\n"