2018-04-22 09:57:20 +00:00
|
|
|
package ui
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"github.com/restic/restic/internal/ui/termstatus"
|
|
|
|
)
|
|
|
|
|
2024-05-21 08:19:14 +00:00
|
|
|
// WrapStdio returns line-buffering replacements for os.Stdout and os.Stderr.
|
|
|
|
// On Close, the remaining bytes are written, followed by a line break.
|
|
|
|
func WrapStdio(term *termstatus.Terminal) (stdout, stderr io.WriteCloser) {
|
|
|
|
return newLineWriter(term.Print), newLineWriter(term.Error)
|
2018-04-22 09:57:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type lineWriter struct {
|
2024-05-21 07:54:42 +00:00
|
|
|
buf bytes.Buffer
|
2018-04-22 09:57:20 +00:00
|
|
|
print func(string)
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ io.WriteCloser = &lineWriter{}
|
|
|
|
|
|
|
|
func newLineWriter(print func(string)) *lineWriter {
|
2024-05-21 07:54:42 +00:00
|
|
|
return &lineWriter{print: print}
|
2018-04-22 09:57:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (w *lineWriter) Write(data []byte) (n int, err error) {
|
|
|
|
n, err = w.buf.Write(data)
|
|
|
|
if err != nil {
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// look for line breaks
|
|
|
|
buf := w.buf.Bytes()
|
2020-10-17 18:23:36 +00:00
|
|
|
i := bytes.LastIndexByte(buf, '\n')
|
|
|
|
if i != -1 {
|
|
|
|
w.print(string(buf[:i+1]))
|
|
|
|
w.buf.Next(i + 1)
|
2018-04-22 09:57:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
2020-10-17 18:15:30 +00:00
|
|
|
func (w *lineWriter) Close() error {
|
2018-04-22 09:57:20 +00:00
|
|
|
if w.buf.Len() > 0 {
|
|
|
|
w.print(string(append(w.buf.Bytes(), '\n')))
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|