Codebase list golang-github-vbauerster-mpb / 329e9f5
remove duplication of clear codes for win and posix, write all at once Kirill Merkushev authored 8 years ago Vladimir Bauer committed 8 years ago
4 changed file(s) with 21 addition(s) and 23 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "bytes"
44 "io"
5 "fmt"
56 )
67
78 // ESC is the ASCII code for escape character
89 const ESC = 27
10
11 var (
12 cursorUp = fmt.Sprintf("%c[%dA", ESC, 1)
13 clearLine = fmt.Sprintf("%c[2K\r", ESC)
14 clearCursorAndLine = cursorUp + clearLine
15 )
916
1017 // Writer is a buffered the writer that updates the terminal.
1118 // The contents of writer will be flushed when Flush is called.
55 "fmt"
66 "syscall"
77 "unsafe"
8 )
9
10 var (
11 cursorUp = fmt.Sprintf("%c[%dA", ESC, 1)
12 clearLine = fmt.Sprintf("%c[2K\r", ESC)
13 clearCursorAndLine = cursorUp + clearLine
8 "strings"
149 )
1510
1611 func (w *Writer) clearLines() {
17 for i := 0; i < w.lineCount; i++ {
18 fmt.Fprint(w.out, clearCursorAndLine)
19 }
12 fmt.Fprint(w.out, strings.Repeat(clearCursorAndLine, w.lineCount))
2013 }
2114
2215 // GetTermSize returns the dimensions of the given terminal.
1717 out := new(bytes.Buffer)
1818 w := cwriter.New(out)
1919
20 testCases := []struct {
20 for _, tcase := range []struct {
2121 input, expectedOutput string
2222 }{
2323 {input: "foo\n", expectedOutput: "foo\n"},
2424 {input: "bar\n", expectedOutput: "foo\n" + clearSequence + "bar\n"},
2525 {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 }
26 } {
27 t.Run(tcase.input, func(t *testing.T) {
28 w.Write([]byte(tcase.input))
29 w.Flush()
30 output := out.String()
31 if output != tcase.expectedOutput {
32 t.Fatalf("want %q, got %q", tcase.expectedOutput, output)
33 }
34 })
3435 }
3536 }
66 "io"
77 "syscall"
88 "unsafe"
9
9 "strings"
1010 "github.com/mattn/go-isatty"
1111 )
1212
5252 func (w *Writer) clearLines() {
5353 f, ok := w.out.(FdWriter)
5454 if ok && !isatty.IsTerminal(f.Fd()) {
55 for i := 0; i < w.lineCount; i++ {
56 fmt.Fprintf(w.out, "%c[%dA", ESC, 1) // move the cursor up
57 fmt.Fprintf(w.out, "%c[2K\r", ESC) // clear the line
58 }
55 fmt.Fprint(w.out, strings.Repeat(clearCursorAndLine, w.lineCount))
5956 return
6057 }
6158 fd := f.Fd()