Codebase list golang-github-vbauerster-mpb / dbca2e1
Merge pull request #4 from alevinval/master (posix-writer) test coverage, simplify logic and faster clearLines() Vladimir Bauer authored 9 years ago GitHub committed 9 years ago
3 changed file(s) with 46 addition(s) and 12 deletion(s). Raw diff Collapse all Expand all
2525
2626 // Flush flushes the underlying buffer
2727 func (w *Writer) Flush() error {
28 // do nothing if buffer is empty
29 if len(w.buf.Bytes()) == 0 {
28 // Do nothing if buffer is empty
29 if w.buf.Len() == 0 {
3030 return nil
3131 }
3232 w.clearLines()
33
34 lines := 0
35 for _, b := range w.buf.Bytes() {
36 if b == '\n' {
37 lines++
38 }
39 }
40 w.lineCount = lines
33 w.lineCount = bytes.Count(w.buf.Bytes(), []byte("\n"))
4134 _, err := w.out.Write(w.buf.Bytes())
4235 w.buf.Reset()
4336 return err
77 "unsafe"
88 )
99
10 var (
11 cursorUp = fmt.Sprintf("%c[%dA", ESC, 1)
12 clearLine = fmt.Sprintf("%c[2K\r", ESC)
13 clearCursorAndLine = cursorUp + clearLine
14 )
15
1016 func (w *Writer) clearLines() {
1117 for i := 0; i < w.lineCount; i++ {
12 fmt.Fprintf(w.out, "%c[%dA", ESC, 1) // move the cursor up
13 fmt.Fprintf(w.out, "%c[2K\r", ESC) // clear the line
18 fmt.Fprint(w.out, clearCursorAndLine)
1419 }
1520 }
1621
0 // +build !windows
1
2 package cwriter_test
3
4 import (
5 "bytes"
6 "fmt"
7 "testing"
8
9 "github.com/vbauerster/mpb/cwriter"
10 )
11
12 var clearSequence = fmt.Sprintf("%c[%dA%c[2K\r", 27, 1, 27)
13
14 // TestWriterPosix by writing and flushing many times. The output buffer
15 // must contain the clearCursor and clearLine sequences.
16 func TestWriterPosix(t *testing.T) {
17 out := new(bytes.Buffer)
18 w := cwriter.New(out)
19
20 testCases := []struct {
21 input, expectedOutput string
22 }{
23 {input: "foo\n", expectedOutput: "foo\n"},
24 {input: "bar\n", expectedOutput: "foo\n" + clearSequence + "bar\n"},
25 {input: "fizz\n", expectedOutput: "foo\n" + clearSequence + "bar\n" + clearSequence + "fizz\n"},
26 }
27 for _, testCase := range testCases {
28 w.Write([]byte(testCase.input))
29 w.Flush()
30 output := out.String()
31 if output != testCase.expectedOutput {
32 t.Fatalf("want %q, got %q", testCase.expectedOutput, output)
33 }
34 }
35 }