Skip to content

Commit

Permalink
cli: don't always use color (#233)
Browse files Browse the repository at this point in the history
Some benefits:
- A user who writes `configlet lint > output.txt` will no longer see
  color codes in that file.
- It becomes cleaner to write integration tests and regression tests
  that involve `configlet lint`.
  • Loading branch information
ee7 authored Mar 24, 2021
1 parent c8bca0b commit fb040f3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
15 changes: 14 additions & 1 deletion src/cli.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 6 additions & 1 deletion src/helpers.nim
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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"

0 comments on commit fb040f3

Please sign in to comment.