summaryrefslogtreecommitdiffstats
path: root/tests/color.sh
blob: 805d2b88691f870872586b58d28157558f85954a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/hint/bash

# Copyright © Tavian Barnes <tavianator@tavianator.com>
# SPDX-License-Identifier: 0BSD

## Colored output

# Common escape sequences
BLD=$'\e[01m'
RED=$'\e[01;31m'
GRN=$'\e[01;32m'
YLW=$'\e[01;33m'
BLU=$'\e[01;34m'
MAG=$'\e[01;35m'
CYN=$'\e[01;36m'
RST=$'\e[0m'

# Check if we should color output to the given fd
color_fd() {
    [ -z "${NO_COLOR:-}" ] && [ -t "$1" ]
}

# Cache the color status for std{out,err}
color_fd 1 && COLOR_STDOUT=1 || COLOR_STDOUT=0
color_fd 2 && COLOR_STDERR=1 || COLOR_STDERR=0

# Save this in case the tests unset PATH
SED=$(command -v sed)

# Filter out escape sequences if necessary
color() {
    if color_fd 1; then
        "$@"
    else
        "$@" | "$SED" $'s/\e\\[[^m]*m//g'
    fi
}