diff --git a/go.mod b/go.mod index df62180..2da0084 100644 --- a/go.mod +++ b/go.mod @@ -5,4 +5,5 @@ go 1.14 require ( github.com/fatih/color v1.7.0 github.com/mattn/go-colorable v0.1.2 // indirect + github.com/mattn/go-isatty v0.0.8 ) diff --git a/spinner.go b/spinner.go index 5ce6870..0b8fc5d 100644 --- a/spinner.go +++ b/spinner.go @@ -16,6 +16,7 @@ package spinner import ( "errors" "fmt" + "github.com/mattn/go-isatty" "io" "os" "runtime" @@ -264,8 +265,21 @@ func (s *Spinner) Active() bool { return s.active } +func isTerminal() bool { + if isatty.IsTerminal(os.Stdout.Fd()){ + return true + } else if isatty.IsCygwinTerminal(os.Stdout.Fd()){ + return true + } + return false +} + // Start will start the indicator. func (s *Spinner) Start() { + if !isTerminal() { + fmt.Printf("\n") + return + } s.mu.Lock() if s.active { s.mu.Unlock() @@ -273,11 +287,10 @@ func (s *Spinner) Start() { } if s.HideCursor && runtime.GOOS != "windows" { // hides the cursor - fmt.Print("\033[?25l") + fmt.Fprint(s.Writer, "\033[?25l") } s.active = true s.mu.Unlock() - go func() { for { for i := 0; i < len(s.chars); i++ { @@ -299,14 +312,14 @@ func (s *Spinner) Start() { var outColor string if runtime.GOOS == "windows" { if s.Writer == os.Stderr { - outColor = fmt.Sprintf("\r%s%s%s ", s.Prefix, s.chars[i], s.Suffix) + outColor = fmt.Sprintf("%s%s ", s.chars[i], s.Suffix) } else { - outColor = fmt.Sprintf("\r%s%s%s ", s.Prefix, s.color(s.chars[i]), s.Suffix) + outColor = fmt.Sprintf("%s%s ", s.chars[i], s.Suffix) } } else { - outColor = fmt.Sprintf("\r%s%s%s ", s.Prefix, s.color(s.chars[i]), s.Suffix) + outColor = fmt.Sprintf("%s%s ", s.chars[i], s.Suffix) } - outPlain := fmt.Sprintf("\r%s%s%s ", s.Prefix, s.chars[i], s.Suffix) + outPlain := fmt.Sprintf("%s%s ", s.chars[i], s.Suffix) fmt.Fprint(s.Writer, outColor) s.lastOutput = outPlain delay := s.Delay @@ -326,12 +339,13 @@ func (s *Spinner) Start() { // Stop stops the indicator. func (s *Spinner) Stop() { s.mu.Lock() + defer fmt.Print("\n") defer s.mu.Unlock() if s.active { s.active = false if s.HideCursor && runtime.GOOS != "windows" { // makes the cursor visible - fmt.Print("\033[?25h") + fmt.Fprint(s.Writer, "\033[?25h") } s.erase() if s.FinalMSG != "" { @@ -393,16 +407,9 @@ func (s *Spinner) UpdateCharSet(cs []string) { // Caller must already hold s.lock. func (s *Spinner) erase() { n := utf8.RuneCountInString(s.lastOutput) - if runtime.GOOS == "windows" { - clearString := "\r" + strings.Repeat(" ", n) + "\r" - fmt.Fprint(s.Writer, clearString) - s.lastOutput = "" - return - } for _, c := range []string{"\b", "\127", "\b", "\033[K"} { // "\033[K" for macOS Terminal fmt.Fprint(s.Writer, strings.Repeat(c, n)) } - fmt.Fprintf(s.Writer, "\r\033[K") // erases to end of line s.lastOutput = "" }