[PATCH 1/3] tracedump: Don't use color when stdout is not a tty

José Fonseca jose.r.fonseca at gmail.com
Wed Oct 19 14:56:10 PDT 2011


On Wed, Oct 19, 2011 at 7:03 PM, Carl Worth <cworth at cworth.org> wrote:
> Previously, if one did an operation like:
>
>        tracedump file.trace > file.dump
>
> The resulting file would be cluttered with escape sequences intending
> to change color. Rather than requiring the user to find the --no-color
> option, we can simply not use any color escape sequences when stdout
> is not a tty.
> ---
>
> On Tue, 11 Oct 2011, Anuj Phogat <anuj.phogat at gmail.com> wrote:
>> it also shows unnecessary escape characters due to color highlighting.
>> This can be avoided by disabling color highlighting at the time of tracedump.
>>
>> tracedump --no-color shape.trace > tracedumpfile
>
> And it's even easier if the tool simply doesn't use the color escapes
> when redirected to a file. Just checking whether stdout is not a tty
> covers this case. That's what this patch does.
>
> We could do something even more clever by checking whether the
> terminal supports the color escape sequence but that would require
> mucking in the terminfo database (yuck!), or linking to a library that
> does that (such as ncurses), or shelling out to a program that could
> do that (such as tput). That all seems quite a bit more complicated
> than this simple patch, so is perhaps not worth it just to set the
> default.
>
> -Carl
>
>  tracedump.cpp |    4 +---
>  1 files changed, 1 insertions(+), 3 deletions(-)
>
> diff --git a/tracedump.cpp b/tracedump.cpp
> index c210a0c..77d779d 100644
> --- a/tracedump.cpp
> +++ b/tracedump.cpp
> @@ -34,9 +34,6 @@
>  #include "trace_parser.hpp"
>
>
> -static bool color = true;
> -
> -
>  static void usage(void) {
>     std::cout <<
>         "Usage: tracedump [OPTION] [TRACE...]\n"
> @@ -51,6 +48,7 @@ static void usage(void) {
>  int main(int argc, char **argv)
>  {
>     int i;
> +    bool color = isatty(1);
>
>     for (i = 1; i < argc; ++i) {
>         const char *arg = argv[i];
> --
> 1.7.7

Carl,

I agree this is preferable as a default behavior, but I'd like to be
able to force color, even on non-tty pipe (e.g., "tracedump foo.trace
| less -R", which I often use).   I think the best would be to mimic
grep's --color/colour=WHEN option:

$ grep --help
[...]
      --color[=WHEN],
      --colour[=WHEN]       use markers to highlight the matching strings;
                            WHEN is `always', `never', or `auto'

where the default is "auto".

Jose


More information about the apitrace mailing list