-
Notifications
You must be signed in to change notification settings - Fork 10
/
arguments.go
92 lines (77 loc) · 1.76 KB
/
arguments.go
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 cmds
import (
"bufio"
"io"
)
// StdinArguments is used to iterate through arguments piped through stdin.
//
// It closely mimics the bufio.Scanner interface but also implements the
// ReadCloser interface.
type StdinArguments interface {
io.ReadCloser
// Scan reads in the next argument and returns true if there is an
// argument to read.
Scan() bool
// Argument returns the next argument.
Argument() string
// Err returns any errors encountered when reading in arguments.
Err() error
}
type arguments struct {
argument string
err error
reader *bufio.Reader
closer io.Closer
}
func newArguments(r io.ReadCloser) *arguments {
return &arguments{
reader: bufio.NewReader(r),
closer: r,
}
}
// Read implements the io.Reader interface.
func (a *arguments) Read(b []byte) (int, error) {
return a.reader.Read(b)
}
// Close implements the io.Closer interface.
func (a *arguments) Close() error {
return a.closer.Close()
}
// WriteTo implements the io.WriterTo interface.
func (a *arguments) WriteTo(w io.Writer) (int64, error) {
return a.reader.WriteTo(w)
}
// Err returns any errors encountered when reading in arguments.
func (a *arguments) Err() error {
if a.err == io.EOF {
return nil
}
return a.err
}
// Argument returns the last argument read in.
func (a *arguments) Argument() string {
return a.argument
}
// Scan reads in the next argument and returns true if there is an
// argument to read.
func (a *arguments) Scan() bool {
if a.err != nil {
return false
}
s, err := a.reader.ReadString('\n')
if err != nil {
a.err = err
if err == io.EOF && len(s) > 0 {
a.argument = s
return true
}
return false
}
l := len(s)
if l >= 2 && s[l-2] == '\r' {
a.argument = s[:l-2]
} else {
a.argument = s[:l-1]
}
return true
}