File: stdio_wrapper.go

package info (click to toggle)
restic 0.18.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 30,824 kB
  • sloc: sh: 3,704; makefile: 50; python: 34
file content (55 lines) | stat: -rw-r--r-- 1,032 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package termstatus

import (
	"bytes"
	"io"
	"sync"
)

// 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 *Terminal) (stdout, stderr io.WriteCloser) {
	return newLineWriter(term.Print), newLineWriter(term.Error)
}

type lineWriter struct {
	m     sync.Mutex
	buf   bytes.Buffer
	print func(string)
}

var _ io.WriteCloser = &lineWriter{}

func newLineWriter(print func(string)) *lineWriter {
	return &lineWriter{print: print}
}

func (w *lineWriter) Write(data []byte) (n int, err error) {
	w.m.Lock()
	defer w.m.Unlock()

	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)
	}

	return n, err
}

func (w *lineWriter) Close() error {
	w.m.Lock()
	defer w.m.Unlock()

	if w.buf.Len() > 0 {
		w.print(string(append(w.buf.Bytes(), '\n')))
	}
	return nil
}