File: read.go

package info (click to toggle)
golang-github-tcnksm-go-input 0.0~git20180404.548a7d7-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 136 kB
  • sloc: makefile: 20
file content (92 lines) | stat: -rw-r--r-- 1,886 bytes parent folder | download
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package input

import (
	"fmt"
	"io"
	"os"
	"os/signal"
	"strings"
)

// readOptions is option for read func
type readOptions struct {
	// mask hides user input and will be matched by maskVal.
	mask    bool
	maskVal string
}

// read reads input from UI.Reader
func (i *UI) read(opts *readOptions) (string, error) {
	i.once.Do(i.setDefault)

	// sigCh is channel which is watch Interruptted signal (SIGINT)
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, os.Interrupt)
	defer signal.Stop(sigCh)

	var resultStr string
	var resultErr error
	doneCh := make(chan struct{})

	go func() {
		defer close(doneCh)

		if opts.mask {
			f, ok := i.Reader.(*os.File)
			if !ok {
				resultErr = fmt.Errorf("reader must be a file")
				return
			}

			i.mask, i.maskVal = opts.mask, opts.maskVal
			resultStr, resultErr = i.rawRead(f)
		} else {
			line, err := i.bReader.ReadString('\n')
			if err != nil && err != io.EOF {
				resultErr = fmt.Errorf("failed to read the input: %s", err)
			}

			resultStr = strings.TrimSuffix(line, LineSep)
			// brute force for the moment
			resultStr = strings.TrimSuffix(line, "\n")
		}
	}()

	select {
	case <-sigCh:
		return "", ErrInterrupted
	case <-doneCh:
		return resultStr, resultErr
	}
}

// rawReadline tries to return a single line, not including the end-of-line
// bytes with raw Mode (without prompting nothing). Or if provided show some
// value instead of actual value.
func (i *UI) rawReadline(f *os.File) (string, error) {
	var resultBuf []byte
	for {
		var buf [1]byte
		n, err := f.Read(buf[:])
		if err != nil && err != io.EOF {
			return "", err
		}

		if n == 0 || buf[0] == '\n' || buf[0] == '\r' {
			break
		}

		if buf[0] == 3 {
			return "", ErrInterrupted
		}

		if i.mask {
			fmt.Fprintf(i.Writer, i.maskVal)
		}

		resultBuf = append(resultBuf, buf[0])
	}

	fmt.Fprintf(i.Writer, "\n")
	return string(resultBuf), nil
}