-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.go
More file actions
97 lines (86 loc) · 1.94 KB
/
script.go
File metadata and controls
97 lines (86 loc) · 1.94 KB
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
93
94
95
96
97
package sqlbless
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/hymkor/csvi"
"github.com/hymkor/sqlbless/internal/misc"
)
type scriptIn struct {
br *bufio.Reader
echo io.Writer
term string
}
func (*scriptIn) CanCloseInTransaction() bool { return true }
func (*scriptIn) ShouldRecordHistory() bool { return false }
func (*scriptIn) SetPrompt(func(io.Writer, int) (int, error)) {}
func (*scriptIn) OnErrorAbort() bool { return true }
func (script *scriptIn) GetKey() (string, error) {
return "", io.EOF
}
func (script *scriptIn) AutoPilotForCsvi() (csvi.Pilot, bool) {
return &misc.CsviNoOperation{}, true
}
func (script *scriptIn) Read(context.Context) ([]string, error) {
if script.br == nil {
return nil, io.EOF
}
var buffer strings.Builder
quoted := 0
for {
ch, _, err := script.br.ReadRune()
if errors.Is(err, io.EOF) {
code := buffer.String()
fmt.Fprintln(script.echo, strings.TrimSpace(code))
script.br = nil
return []string{code}, nil
}
if err != nil {
return nil, err
}
if ch == '\r' {
continue
} else if ch == '\'' {
quoted ^= 1
} else if ch == '"' {
quoted ^= 2
}
buffer.WriteRune(ch)
if quoted == 0 {
code := buffer.String()
term := script.term
if _, ok := misc.HasTerm(code, term); ok {
fmt.Fprintln(script.echo, strings.TrimSpace(code))
return []string{code}, nil
}
}
}
}
func (ss *session) StartFromStdin(ctx context.Context) error {
script := &scriptIn{
br: bufio.NewReader(os.Stdin),
echo: ss.stdErr,
term: ss.Term,
}
return ss.Loop(ctx, script)
}
func (ss *session) Start(ctx context.Context, fname string) error {
if fname == "-" {
return ss.StartFromStdin(ctx)
}
fd, err := os.Open(fname)
if err != nil {
return err
}
defer fd.Close()
script := &scriptIn{
br: bufio.NewReader(fd),
echo: ss.stdErr,
term: ss.Term,
}
return ss.Loop(ctx, script)
}