Skip to content

Commit

Permalink
feat(output): add WithTTY to assume tty
Browse files Browse the repository at this point in the history
Fixes: #105
Fixes: #108
  • Loading branch information
aymanbagabas committed Mar 6, 2023
1 parent 2f39c0a commit cb66b65
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
19 changes: 15 additions & 4 deletions output.go
Expand Up @@ -26,6 +26,7 @@ type Output struct {
tty io.Writer
environ Environ

isTty bool
unsafe bool
cache bool
fgSync *sync.Once
Expand Down Expand Up @@ -85,21 +86,21 @@ func NewOutput(tty io.Writer, opts ...OutputOption) *Output {
return o
}

// WithEnvironment returns a new Output for the given environment.
// WithEnvironment returns a new OutputOption for the given environment.
func WithEnvironment(environ Environ) OutputOption {
return func(o *Output) {
o.environ = environ
}
}

// WithProfile returns a new Output for the given profile.
// WithProfile returns a new OutputOption for the given profile.
func WithProfile(profile Profile) OutputOption {
return func(o *Output) {
o.Profile = profile
}
}

// WithColorCache returns a new Output with fore- and background color values
// WithColorCache returns a new OutputOption with fore- and background color values
// pre-fetched and cached.
func WithColorCache(v bool) OutputOption {
return func(o *Output) {
Expand All @@ -111,9 +112,19 @@ func WithColorCache(v bool) OutputOption {
}
}

// WithUnsafe returns a new Output with unsafe mode enabled. Unsafe mode doesn't
// WithTTY returns a new OutputOption to assume whether or not the output is a TTY.
// This is useful when mocking console output.
func WithTTY(v bool) OutputOption {
return func(o *Output) {
o.isTty = v
}
}

// WithUnsafe returns a new OutputOption with unsafe mode enabled. Unsafe mode doesn't
// check whether or not the terminal is a TTY.
//
// This option supersedes WithTTY.
//
// This is useful when mocking console output and enforcing ANSI escape output
// e.g. on SSH sessions.
func WithUnsafe() OutputOption {
Expand Down
2 changes: 1 addition & 1 deletion termenv.go
Expand Up @@ -25,7 +25,7 @@ const (
)

func (o *Output) isTTY() bool {
if o.unsafe {
if o.isTty || o.unsafe {
return true
}
if len(o.environ.Getenv("CI")) > 0 {
Expand Down
10 changes: 10 additions & 0 deletions termenv_test.go
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"image/color"
"io/ioutil"
"os"
"strings"
"testing"
Expand Down Expand Up @@ -405,3 +406,12 @@ func TestEnableVirtualTerminalProcessing(t *testing.T) {
t.Fatalf("expected <nil>, got %v", err)
}
}

func TestWithTTY(t *testing.T) {
for _, v := range []bool{true, false} {
o := NewOutput(ioutil.Discard, WithTTY(v))
if o.isTTY() != v {
t.Fatalf("expected WithTTY(%t) to set isTTY to %t", v, v)
}
}
}

0 comments on commit cb66b65

Please sign in to comment.