Skip to content

Commit

Permalink
Merge pull request #182 from fatih/expose-set-writers
Browse files Browse the repository at this point in the history
color: expose `SetWriter` and `UnsetWriter`
  • Loading branch information
fatih committed Jan 22, 2023
2 parents 6378f62 + 7310c74 commit 212f8c5
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions color.go
Expand Up @@ -163,7 +163,10 @@ func (c *Color) unset() {
Unset()
}

func (c *Color) setWriter(w io.Writer) *Color {
// SetWriter is used to set the SGR sequence with the given io.Writer. This is
// a low-level function, and users should use the higher-level functions, such
// as color.Fprint, color.Print, etc.
func (c *Color) SetWriter(w io.Writer) *Color {
if c.isNoColorSet() {
return c
}
Expand All @@ -172,7 +175,9 @@ func (c *Color) setWriter(w io.Writer) *Color {
return c
}

func (c *Color) unsetWriter(w io.Writer) {
// UnsetWriter resets all escape attributes and clears the output with the give
// io.Writer. Usually should be called after SetWriter().
func (c *Color) UnsetWriter(w io.Writer) {
if c.isNoColorSet() {
return
}
Expand All @@ -197,8 +202,8 @@ func (c *Color) Add(value ...Attribute) *Color {
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
c.SetWriter(w)
defer c.UnsetWriter(w)

return fmt.Fprint(w, a...)
}
Expand All @@ -220,8 +225,8 @@ func (c *Color) Print(a ...interface{}) (n int, err error) {
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
c.SetWriter(w)
defer c.UnsetWriter(w)

return fmt.Fprintf(w, format, a...)
}
Expand All @@ -241,8 +246,8 @@ func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
c.SetWriter(w)
defer c.UnsetWriter(w)

return fmt.Fprintln(w, a...)
}
Expand Down

0 comments on commit 212f8c5

Please sign in to comment.