diff --git a/cwriter/writer.go b/cwriter/writer.go index 61be02b..1fd9d95 100644 --- a/cwriter/writer.go +++ b/cwriter/writer.go @@ -3,10 +3,17 @@ import ( "bytes" "io" + "fmt" ) // ESC is the ASCII code for escape character const ESC = 27 + +var ( + cursorUp = fmt.Sprintf("%c[%dA", ESC, 1) + clearLine = fmt.Sprintf("%c[2K\r", ESC) + clearCursorAndLine = cursorUp + clearLine +) // Writer is a buffered the writer that updates the terminal. // The contents of writer will be flushed when Flush is called. diff --git a/cwriter/writer_posix.go b/cwriter/writer_posix.go index a39bb7b..cd166e0 100644 --- a/cwriter/writer_posix.go +++ b/cwriter/writer_posix.go @@ -6,18 +6,11 @@ "fmt" "syscall" "unsafe" -) - -var ( - cursorUp = fmt.Sprintf("%c[%dA", ESC, 1) - clearLine = fmt.Sprintf("%c[2K\r", ESC) - clearCursorAndLine = cursorUp + clearLine + "strings" ) func (w *Writer) clearLines() { - for i := 0; i < w.lineCount; i++ { - fmt.Fprint(w.out, clearCursorAndLine) - } + fmt.Fprint(w.out, strings.Repeat(clearCursorAndLine, w.lineCount)) } // GetTermSize returns the dimensions of the given terminal. diff --git a/cwriter/writer_posix_test.go b/cwriter/writer_posix_test.go index 30e6c25..c782dff 100644 --- a/cwriter/writer_posix_test.go +++ b/cwriter/writer_posix_test.go @@ -18,19 +18,20 @@ out := new(bytes.Buffer) w := cwriter.New(out) - testCases := []struct { + for _, tcase := range []struct { input, expectedOutput string }{ {input: "foo\n", expectedOutput: "foo\n"}, {input: "bar\n", expectedOutput: "foo\n" + clearSequence + "bar\n"}, {input: "fizz\n", expectedOutput: "foo\n" + clearSequence + "bar\n" + clearSequence + "fizz\n"}, - } - for _, testCase := range testCases { - w.Write([]byte(testCase.input)) - w.Flush() - output := out.String() - if output != testCase.expectedOutput { - t.Fatalf("want %q, got %q", testCase.expectedOutput, output) - } + } { + t.Run(tcase.input, func(t *testing.T) { + w.Write([]byte(tcase.input)) + w.Flush() + output := out.String() + if output != tcase.expectedOutput { + t.Fatalf("want %q, got %q", tcase.expectedOutput, output) + } + }) } } diff --git a/cwriter/writer_windows.go b/cwriter/writer_windows.go index 64a68f6..a08f37a 100644 --- a/cwriter/writer_windows.go +++ b/cwriter/writer_windows.go @@ -7,7 +7,7 @@ "io" "syscall" "unsafe" - + "strings" "github.com/mattn/go-isatty" ) @@ -53,10 +53,7 @@ func (w *Writer) clearLines() { f, ok := w.out.(FdWriter) if ok && !isatty.IsTerminal(f.Fd()) { - for i := 0; i < w.lineCount; i++ { - fmt.Fprintf(w.out, "%c[%dA", ESC, 1) // move the cursor up - fmt.Fprintf(w.out, "%c[2K\r", ESC) // clear the line - } + fmt.Fprint(w.out, strings.Repeat(clearCursorAndLine, w.lineCount)) return } fd := f.Fd()