On Tue, 29 Mar 2016 09:08:16 +0100
roger peppe <
rogp...@gmail.com> wrote:
> One thing: please respect the value of $TERM.
> If it's "dumb", then please don't output the ANSI control codes.
> Not everyone uses an ANSI terminal for shell output
> and it's frustrating when commands don't provide a way
> of silencing the noise.
It's not that simple. The names of terminal types are free-form,
and it's somewhat customary to have user-provided terminal descriptions.
Instead, one should query the terminal description file for the number
of colors the terminal supports. Ncurses comes with a dedicated binary,
`tput` which can be used for this -- say, on my current system I have:
~% echo $TERM
rxvt-unicode-256color
~% tput colors
256
~% TERM=dumb tput colors
-1
~%
The `tput` binary uses libtinfo library which is a part of ncurses, and
is responsible for accessing the terminal description database and
parsing its data.
termbox-go contains reasonable amount of code to query this database
but my cursory look at it failed to locate anything related to querying
this parameter. I'd say extending termbox-go with the approach
libtinfo implements to read the number of colors supported by a
terminal could work. ;-)
> You should probably also consider turning off the colours
> if the output is not a terminal, as it's useful to be able
> to use grep.
That's simpler -- as Alex Bligh suggested, the isatty() libc function
is typically used for this.
One problem with this is that it's a libc function and is hence
unavailable to Go unless cgo is used (which would be very much
desirable to avoid).
At least on Linux, isatty() internally calls fstat() on the file
descriptor associated with the stdout and them sees if the "mode" field
of the returned "stat data" block has bits indicating it's a "character
special" device set. On Linux, this mask, S_IFCHR, is defined to be
0020000. I don't know is this bitmask is portable or platform-specific
though.
In pure Go, Fstat is available via the syscall standard package.
I'm also pretty sure specialized packages for terminal handling, like,
say, termbox-go, should already contain code which mimics isatty().