Skip to content
File

Blob: src/workerd/util/color-util.h

cpp39 lines
1// Copyright (c) 2017-2022 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5#pragma once
6 
7#include <kj/string.h>
8 
9#include <cstdlib>
10 
11namespace workerd {
12 
13enum class ColorMode {
14 // Always output colors to the console
15 ENABLED,
16 // Output colors to the console if it's a TTY
17 ENABLED_IF_TTY,
18 // Never output colors to the console
19 DISABLED
20};
21 
22// Returns whether we can output color to the console. Even if this returns `true`,
23// we'll only write color codes if the output file is a TTY.
24// TODO(someday): adopt more of Node.js's checks:
25// https://github.com/nodejs/node/blob/ac2a68c/lib/internal/tty.js#L106
26static ColorMode permitsColor() {
27 const char* forceColorValue = getenv("FORCE_COLOR");
28 if (forceColorValue != nullptr) {
29 auto f = kj::StringPtr(forceColorValue);
30 auto enabled = f == "" || f == "1" || f == "2" || f == "3" || f == "true";
31 return enabled ? ColorMode::ENABLED : ColorMode::DISABLED;
32 } else {
33 auto enabled = getenv("NO_COLOR") == nullptr && getenv("CI") == nullptr;
34 return enabled ? ColorMode::ENABLED_IF_TTY : ColorMode::DISABLED;
35 }
36}
37 
38} // namespace workerd