diff options
author | Ben Smith <binjimin@gmail.com> | 2017-06-23 19:25:32 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2017-06-23 19:25:32 -0700 |
commit | b2613e132d93372bd75c640dd4d7505a81f707f7 (patch) | |
tree | c5c529d46bc6439cdf4975aefcf186287a064054 /src/color.cc | |
parent | 29e8e9ee0068b0f90f30c69c4f6c0c3fd30bf96e (diff) | |
download | wabt-b2613e132d93372bd75c640dd4d7505a81f707f7.tar.gz wabt-b2613e132d93372bd75c640dd4d7505a81f707f7.tar.bz2 wabt-b2613e132d93372bd75c640dd4d7505a81f707f7.zip |
Add color output in SourceErrorHandler (#517)
This is currently only supported where VT100 escape sequences work. We
assume that if `isatty` is true then color will be supported. This logic will
likely need to be improved, but this is a good start.
This PR also adds support for passing an environment variable to a test
via `ENV`. This is used to test the `FORCE_COLOR` environment variable.
Diffstat (limited to 'src/color.cc')
-rw-r--r-- | src/color.cc | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/src/color.cc b/src/color.cc new file mode 100644 index 00000000..f1657728 --- /dev/null +++ b/src/color.cc @@ -0,0 +1,84 @@ +/* + * Copyright 2017 WebAssembly Community Group participants + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "color.h" + +#include <cstdlib> + +#include "common.h" + +#if _WIN32 +#include <io.h> +#include <windows.h> +#elif HAVE_UNISTD_H +#include <unistd.h> +#endif + +namespace wabt { + +Color::Color(FILE* file, bool enabled) : file_(file) { + enabled_ = enabled && SupportsColor(file_); +} + +// static +bool Color::SupportsColor(FILE* file) { + char* force = getenv("FORCE_COLOR"); + if (force) { + return atoi(force) != 0; + } + +#if _WIN32 + + { +#if HAVE_WIN32_VT100 + HANDLE handle; + if (file == stdout) { + handle = GetStdHandle(STD_OUTPUT_HANDLE); + } else if (file == stderr) { + handle = GetStdHandle(STD_ERROR_HANDLE); + } else { + return false; + } + DWORD mode; + if (!_isatty(_fileno(file)) || !GetConsoleMode(handle, mode) || + !SetConsoleMode(handle, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) { + return false; + } + return true; +#else + // TODO(binji): Support older Windows by using SetConsoleTextAttribute? + return false; +#endif + } + +#elif HAVE_UNISTD_H + + return isatty(fileno(file)); + +#else + + return false; + +#endif +} + +void Color::WriteCode(const char* code) const { + if (enabled_) { + fputs(code, file_); + } +} + +} // namespace wabt |