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
| 25 | 25 |
|
| 26 | 26 |
// Flush flushes the underlying buffer
|
| 27 | 27 |
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 {
|
| 30 | 30 |
return nil
|
| 31 | 31 |
}
|
| 32 | 32 |
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"))
|
| 41 | 34 |
_, err := w.out.Write(w.buf.Bytes())
|
| 42 | 35 |
w.buf.Reset()
|
| 43 | 36 |
return err
|
| 7 | 7 |
"unsafe"
|
| 8 | 8 |
)
|
| 9 | 9 |
|
|
10 |
var (
|
|
11 |
cursorUp = fmt.Sprintf("%c[%dA", ESC, 1)
|
|
12 |
clearLine = fmt.Sprintf("%c[2K\r", ESC)
|
|
13 |
clearCursorAndLine = cursorUp + clearLine
|
|
14 |
)
|
|
15 |
|
| 10 | 16 |
func (w *Writer) clearLines() {
|
| 11 | 17 |
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)
|
| 14 | 19 |
}
|
| 15 | 20 |
}
|
| 16 | 21 |
|
|
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 |
}
|