fatih / color Goto Github PK
View Code? Open in Web Editor NEWColor package for Go (golang)
Home Page: https://pkg.go.dev/github.com/fatih/color
License: MIT License
Color package for Go (golang)
Home Page: https://pkg.go.dev/github.com/fatih/color
License: MIT License
quick shout out to you for this amazing package this truly makes my cli tools look very colorful and amazing. Sadly there is a 'But', I tried using the compiled and executable binary of the go build
and there some weird I am guessing unencoded symbols surrounding the words of text that is supposed to be colored.
EX:
�[31merror cache:�[0m run `cache --help` command to see how to use cache and what commands to use.
If you could help understand that or maybe find a way to fix it that would be coolio
$ go run color.go > color.log
$ vi color.log
1 ^[[36mPrints text in cyan.
2 ^[[0m^[[34mPrints text in blue.
3 ^[[0m^[[31mWe have red
4 ^[[0m^[[35mAnd many others ..
5 ^[[0m
When searching for "golang color" on GitHub, this repository is not listed. If I instead search for "go color", I do indeed find it.
I'd recommend doing something like mitchellh/colorstring, such as "Color package for Go (golang) http://godoc.org/github.com/fatih/color". I believe that this will make it easier for people to discover this repo.
Hello.
I'm trying to use color
library v1.4.0 as a dependency via dep
tool. It resolves dependencies well, but there is an issue with go-isatty
dependency.
undefined: isatty.IsCygwinTerminal
As I understand, isatty is released with a tag which does not have the latest changes.
https://github.com/mattn/go-isatty/tree/v0.0.1
Would it be possible to force colour output without a terminal i.e. in a pipe? This would allow grep-ing for errors while maintaining useful colourised output.
This would provide the opposite functionality to https://github.com/fatih/color#disable-color - perhaps usage could look similar
var flagForceColor = flag.Bool("force-color", false, "Force color output")
if *flagForceColor {
color.ForceColor = true // forces colorized output, even without a terminal attached
}
As a data point, grep
also implements this with a flag:
$ grep --help | grep color -A 2
--color[=WHEN],
--colour[=WHEN] use markers to highlight the matching strings;
WHEN is 'always', 'never', or 'auto'
This feature request is spawned from a dependent project https://github.com/wercker/stern/issues/33#issuecomment-289045171
If you do:
fmt.Println(color.RedString("%"))
This is printed (in red):
%!(NOVERB)
This should be printed (in red):
%
The wrong output is displayed even when color.NoColor
is set to true.
Hi, I'm evaluating this package and I have a question around disabling colors easily if the detected terminal/output/pipe/etc doesn't support colors?
Hi
I know with a name like "color" almost anything else is out of scope but I was wondering if you would consider adding support for "bold", "faint", "Italic", and "Underline".
Or perhaps they can fit in into an standalone package?
Background color don't properly clear if using Println or Printf
func TestLineClear(t *testing.T) {
New(BgWhite).Printf("Printf - Solid white\n")
fmt.Println("Line should be normal")
fmt.Println()
New(BgWhite).Println("Println - Solid white")
fmt.Println("Line should be normal")
fmt.Println()
New(BgWhite).Print("Print - Solid white\n")
fmt.Println("Line should be normal")
}
Here a pull request in case you'll want to use vgo.
Right now, if we are going to use Sprint, Sprintf, Sprintln outputs and
perform further formatting on the returned string as:
fmt.Printf("%-10s", color.New(color.FgYellow).Sprint("hello"))
it may not give the correct padding.
To handle such cases, implement a set of functions that can return
formattable objects outside color/
package.
To begin with, I might propose the following:
Implement a set of functions similar to Sprint, Sprintf, Sprintln.
And another set of functions similar to SprintFunc, SprintfFunc SprintlnFunc
that returns an object implementing fmt.Formatter{}
interface.
If it make sense, I can do a draft implementation and raise a pull request.
Thanks,
When calling Red("cat%dog")
or RedString("cat%dog")
without additional args, the string is interpreted as a format. The result is cat%!d(MISSING)dog
. This is unexpected behavior. Or as @davecheney said, "Wow, what an API footgun."
I ran into this while upgrading some tests to check for colorized output. Tests worked fine in the package, but go test ./...
fails. You can reproduce this easily in this repo.
tests pass
go test
tests fail
go test ./...
Please use semantic versioning:
Hello. I've tried using the Faint attribute for normally coloured console output. On Linux it works as expected: text is greyer and harder to read. On windows surprisingly the opposite is true: FgWhite is greyer and harder to read than Faint is.
I'm not sure if I should report that issue here, or on mattn's go-colorable.
Hi @fatih
Thanks a lot for your color package.
It works great on Linux, but there's a problem under Windows.
package main
import (
"github.com/fatih/color"
"fmt"
)
func main() {
color.Red("1. We have red")
fmt.Println(color.RedString("2. We have red"))
}
The first line is printed in red, but not the second one:
I'm using the default shell (c:\Windows\system32\cmd.exe) on Windows 7.
I'm using the color._String
functions to color sub parts of a string that have already been colored.
package main
import (
"fmt"
"github.com/fatih/color"
)
func main() {
fmt.Println(color.CyanString("1" + color.RedString("2") + "3"))
}
It looks like the existing behavior is probably intentional, because this piece of code clearly shows the wrap function unformating the color. I'm not sure if it would be feasible to support this scenario or even if it was if that'd be outside the intended scope of this package, so I'm not assuming this should change, but wanted to open a discussion about it. I'd be up for taking a stab at it if the consensus is this would be welcomed. Some similar packages in other languages do allow nesting of colors. e.g. https://github.com/junegunn/ansi256#nesting
Lines 357 to 363 in 5df930a
Lines 365 to 367 in 5df930a
Lines 369 to 371 in 5df930a
#51 and #50 are an improper method of determining whether a terminal supports color. There are many dumb terms that support color, and there are non-dumb terminals that don't support color.
I currently use a dumb terminal as my main terminal, and all apps built with faith/color don't show color, but all other applications I use seem to work fine.
The proper way to do this is to use the terminfo database, for a simple example:
tput colors
shows how many colors this terminal supports.
Simple workaround to avoid loosing colors:
if os.Getenv("TERM") == "dumb" && isatty.IsTerminal(os.Stdout.Fd()) {
color.NoColor = false
}
I am using Git Bash and wanted to color the output of my program, but I'm getting this:
?[36mMSathieu C:\Users\MSathieu\go\src\github.com\MSathieu\Gosh $?[0m
.
e.g.:
cyan := color.New(color.FgCyan).SprintFunc()
fmt.Printf("%-5v%v\n", cyan("foo"), "bar")
should print "foo bar" (with 2 spaces) but prints "foobar"
Once a color is set to a string there is no way to undo that. It is required while writing to file. So something like this would be great.
func (c *Color) Uncolorize(str string) string {
// if str is colorized uncolorize it and return
}
It looks like the source code uses fmt.Println for everything, but what if I want things to be on the same line just in a different print statement. For example, if I wanted to use two colors on the same line.
How would I do this? Or do I have to edit the source file?
Thanks!
I faced race condition. I think fixing this may solve:
// Set sets the SGR sequence.
func (c *Color) Set() *Color {
c.Lock()
if c.isNoColorSet() {
return c
}
fmt.Fprintf(Output, c.format())
return c
}
func (c *Color) unset() {
if c.isNoColorSet() {
return
}
Unset()
c.Unlock()
}
I tried using this within a go test function and was not able to get the color in the terminal. It works within a regular main() function.
func Test_Color(t *testing.T) {
color.Set(color.FgWhite, color.Bold)
color.Cyan("Prints text in cyan.")
fmt.Println("This is white in color")
}
We are facing an issue while using this package while golang.org/x/sys/unix
is pinned to a really old version.
# go build
# [hidden]/vendor/golang.org/x/crypto/ssh/terminal
vendor/golang.org/x/crypto/ssh/terminal/util.go:30: undefined: unix.IoctlGetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:38: undefined: unix.IoctlGetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:54: undefined: unix.IoctlSetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:64: undefined: unix.IoctlGetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:75: undefined: unix.IoctlSetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:80: undefined: unix.IoctlGetWinsize
vendor/golang.org/x/crypto/ssh/terminal/util.go:98: undefined: unix.IoctlGetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:107: undefined: unix.IoctlSetTermios
vendor/golang.org/x/crypto/ssh/terminal/util.go:112: undefined: unix.IoctlSetTermios
So we've pinned the package golang.org/x/sys/unix
to latest version and our project builds. The reason for this issue is that your version to old to provide the needed methods and glide resolves the versions listed in the manifests of packages.
Maybe you need to check if it is possible to update your manifest to newer versions of your packages.
It would be wonderful if you could turn off color like @mjibson did in cortesi/termlog#3. I don't develop with go, but it seems like his change is a good compromise to respect $TERM without breaking backwards compatibility:
var NoColor = !isatty.IsTerminal(os.Stdout.Fd()) || os.Getenv("TERM") == "dumb"
Anybody who sets TERM=dumb is actively trying to communicate with programs that the output is not a terminal which seems in line with the IsTerminal() test.
Please tell others about how to respect $TERM, thanks!
Hello Fatih!
i am using code like this
`
code:
mw := io.MultiWriter(os.Stdout, file)
Trace = log.New(file,
"TRACE: ",
log.Ldate|log.Ltime|log.Lshortfile)
Trace.SetOutput(mw)
`
Am I able use your module in my code ?
Colored output seems to be disabled because color package is not detecting the CI system CLIs. It looks like many is setting a CI
env variable we can look for and enable colors on the known providers. Also see the reference at https://github.com/chalk/supports-color/blob/master/index.js#L66.
Color uses the fmt package which is not safe to be used across multiple concurrent goroutines.
We need to either
We have been using the library in https://github.com/michaelsauter/crane for a while, but a recent change you made (namely making color.Set()
private) broke our build which does not use any vendoring mechanism. We worked around that with michaelsauter/crane#187, but I am concerned about potential breaking changes in the future. Do you have any policy regarding backward-compatibility?
Thanks for your work!
Backspace character is not clearing previously output characters.
See screenshot:
I'm running zsh on OSX.
Here's the program to repro:
package main
import (
"fmt"
"github.com/fatih/color"
)
func main() {
fmt.Println("with fmt:")
fmt.Print("Hello...")
fmt.Println("\b\b\b, World!\n")
fmt.Println("with color:")
color.Cyan("Hello...")
color.Cyan("\b\b\b, World!\n")
}
Have a function that will read the string and it changes the color whenever inside the string there is a $ and one color. I already did this (pretty crappy and slow) but you can improve on this idea:
var awaitingColor bool
colorPrint := color.New(color.FgWhite)
for _, character := range sError {
if awaitingColor {
switch character {
case 'w':
colorPrint = color.New(color.FgWhite)
break
case 'r':
colorPrint = color.New(color.FgRed)
break
case 'y':
colorPrint = color.New(color.FgYellow)
break
case 'b':
colorPrint = color.New(color.FgBlue)
break
}
awaitingColor = false
} else if character == '$' {
awaitingColor = true
} else {
colorPrint.Print(string(character))
}
}
add Errorf
and Errorffunc
as target to fmt.Errorf
Not just v1.2
, for better compatibility with vendoring tools.
I'd like to use 256 color or even truecolor escape codes to create nicer-looking CLI tools, but this library only seems to support the 16 traditional ANSI colors. As terminal support for truecolor is quite good by now (including on Windows 10, in my testing), it would be useful to see support for those escape codes.
Please consider adding this feature for colorizing the keyboard input too.
Please see golang/go#18153.
Only go test
is affected.
Like the color.NoColor
flag it would be good to have a global flag to force color output.
use case: Currently if I pipe the output to less
the color is automatically disabled because it is not detected as a tty. I would like to do something like myApp --color | less -r
I have opened the issue here
golang/go#18277
It seems like for Go v > 1.6 when i install your module by go get github.com/fatih/color
it later cannot be imported in file. For Go version 1.5 it works as expected
What do you think about PrintlnFunc
returning a func compatible to fmt.Println
regarding to the return params?
Something like this:
// PrintlnFunc returns a new function that prints the passed arguments as
// colorized with color.Println().
func (c *Color) PrintlnFunc() func(a ...interface{}) (int, error) {
return func(a ...interface{}) (int, error) {
return c.Println(a...)
}
}```
Hi @fatih . I'm a graphic designer. I wanted to contribute to your project for free, i'm waiting your feedback. Thanks .. Best Regard. Mirza Zulfan.
I checked the terminal settings. ANSI colors are enabled, and other terminal utilities (bower specifically) seem to be outputting colors correctly. I've tested with SprintFunc and color.Cyan(). Nothing seems to be outputting color.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.