Skip to content

Commit a901fc4

Browse files
authored
[utils] Add a util to help printing with colors. NFC (#4665)
* [utils] Add a util to help printing with colors. NFC * Update macro guard for consistency. * add some doc-comments.
1 parent c85ea1f commit a901fc4

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

include/swift/Basic/ColorUtils.h

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//===--- ColorUtils.h - -----------------------------------------*- C++ -*-===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See http://swift.org/LICENSE.txt for license information
9+
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
//
13+
// This file defines an 'OSColor' class for helping printing colorful outputs
14+
// to the terminal.
15+
//
16+
//===----------------------------------------------------------------------===//
17+
18+
#ifndef SWIFT_BASIC_COLORUTILS_H
19+
#define SWIFT_BASIC_COLORUTILS_H
20+
21+
#include "llvm/Support/raw_ostream.h"
22+
23+
namespace swift {
24+
25+
/// RAII class for setting a color for a raw_ostream and resetting when it goes
26+
/// out-of-scope.
27+
class OSColor {
28+
llvm::raw_ostream &OS;
29+
bool HasColors;
30+
public:
31+
OSColor(llvm::raw_ostream &OS, llvm::raw_ostream::Colors Color) : OS(OS) {
32+
HasColors = OS.has_colors();
33+
if (HasColors)
34+
OS.changeColor(Color);
35+
}
36+
~OSColor() {
37+
if (HasColors)
38+
OS.resetColor();
39+
}
40+
41+
OSColor &operator<<(char C) { OS << C; return *this; }
42+
OSColor &operator<<(llvm::StringRef Str) { OS << Str; return *this; }
43+
};
44+
45+
} // namespace swift
46+
47+
#endif // SWIFT_BASIC_COLORUTILS_H

0 commit comments

Comments
 (0)