Improve raw_ostream so that you can "write" colors using operator<<

1. raw_ostream supports ANSI colors so that you can write messages to
the termina with colors. Previously, in order to change and reset
color, you had to call `changeColor` and `resetColor` functions,
respectively.

So, if you print out "error: " in red, for example, you had to do
something like this:

  OS.changeColor(raw_ostream::RED);
  OS << "error: ";
  OS.resetColor();

With this patch, you can write the same code as follows:

  OS << raw_ostream::RED << "error: " << raw_ostream::RESET;

2. Add a boolean flag to raw_ostream so that you can disable colored
output. If you disable colors, changeColor, operator<<(Color),
resetColor and other color-related functions have no effect.

Most LLVM tools automatically prints out messages using colors, and
you can disable it by passing a flag such as `--disable-colors`.
This new flag makes it easy to write code that works that way.

Differential Revision: https://reviews.llvm.org/D65564

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@367649 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Rui Ueyama
2019-08-02 04:48:30 +00:00
parent be5ae1bbe6
commit 9a106d08cf
12 changed files with 89 additions and 39 deletions
+4 -3
View File
@@ -22,6 +22,8 @@ WithColor::WithColor(raw_ostream &OS, HighlightColor Color, bool DisableColors)
: OS(OS), DisableColors(DisableColors) {
// Detect color from terminal type unless the user passed the --color option.
if (colorsEnabled()) {
OS.enable_colors();
switch (Color) {
case HighlightColor::Address:
OS.changeColor(raw_ostream::YELLOW);
@@ -104,10 +106,9 @@ bool WithColor::colorsEnabled() {
return UseColor == cl::BOU_TRUE;
}
WithColor &WithColor::changeColor(raw_ostream::Colors Color, bool Bold,
bool BG) {
WithColor &WithColor::changeColor(raw_ostream::Color C, bool Bold, bool BG) {
if (colorsEnabled())
OS.changeColor(Color, Bold, BG);
OS.changeColor(C, Bold, BG);
return *this;
}