Files
restic/internal/ui/termstatus/stdio_wrapper.go

50 lines
753 B
Go
Raw Normal View History

package termstatus
2018-04-22 11:57:20 +02:00
import (
"bytes"
"io"
"sync"
2018-04-22 11:57:20 +02:00
)
type lineWriter struct {
m sync.Mutex
buf bytes.Buffer
2018-04-22 11:57:20 +02:00
print func(string)
}
var _ io.WriteCloser = &lineWriter{}
func newLineWriter(print func(string)) *lineWriter {
return &lineWriter{print: print}
2018-04-22 11:57:20 +02:00
}
func (w *lineWriter) Write(data []byte) (n int, err error) {
w.m.Lock()
defer w.m.Unlock()
2018-04-22 11:57:20 +02:00
n, err = w.buf.Write(data)
if err != nil {
return n, err
}
// look for line breaks
buf := w.buf.Bytes()
i := bytes.LastIndexByte(buf, '\n')
if i != -1 {
w.print(string(buf[:i+1]))
w.buf.Next(i + 1)
2018-04-22 11:57:20 +02:00
}
return n, err
}
func (w *lineWriter) Close() error {
w.m.Lock()
defer w.m.Unlock()
2018-04-22 11:57:20 +02:00
if w.buf.Len() > 0 {
w.print(string(append(w.buf.Bytes(), '\n')))
}
return nil
}