-
Notifications
You must be signed in to change notification settings - Fork 148
/
gore.go
146 lines (125 loc) · 2.32 KB
/
gore.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package gore
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// Version of gore.
const Version = "0.5.7"
// Gore ...
type Gore struct {
autoImport bool
extFiles string
packageName string
outWriter, errWriter io.Writer
}
// New Gore
func New(opts ...Option) *Gore {
g := &Gore{outWriter: os.Stdout, errWriter: os.Stderr}
for _, opt := range opts {
opt(g)
}
return g
}
// Run ...
func (g *Gore) Run() error {
s, err := NewSession(g.outWriter, g.errWriter)
defer s.Clear()
if err != nil {
return err
}
s.autoImport = g.autoImport
fmt.Fprintf(g.errWriter, "gore version %s :help for help\n", Version)
if g.extFiles != "" {
extFiles := strings.Split(g.extFiles, ",")
s.includeFiles(extFiles)
}
if g.packageName != "" {
if err := s.includePackage(g.packageName); err != nil {
return err
}
}
rl := newContLiner()
defer rl.Close()
var historyFile string
home, err := homeDir()
if err != nil {
errorf("home: %s", err)
} else {
historyFile = filepath.Join(home, "history")
f, err := os.Open(historyFile)
if err != nil {
if !os.IsNotExist(err) {
errorf("%s", err)
}
} else {
_, err := rl.ReadHistory(f)
if err != nil {
errorf("while reading history: %s", err)
}
f.Close()
}
}
rl.SetWordCompleter(s.completeWord)
for {
in, err := rl.Prompt()
if err != nil {
if err == io.EOF {
break
}
return err
}
if in == "" {
continue
}
if err := rl.Reindent(); err != nil {
fmt.Fprintf(g.errWriter, "error: %s\n", err)
rl.Clear()
continue
}
err = s.Eval(in)
if err != nil {
if err == ErrContinue {
continue
} else if err == ErrQuit {
break
} else if err != ErrCmdRun {
rl.Clear()
continue
}
}
rl.Accepted()
}
if historyFile != "" {
err := os.MkdirAll(filepath.Dir(historyFile), 0o755)
if err != nil {
errorf("%s", err)
} else {
f, err := os.Create(historyFile)
if err != nil {
errorf("%s", err)
} else {
_, err := rl.WriteHistory(f)
if err != nil {
errorf("while saving history: %s", err)
}
f.Close()
}
}
}
return nil
}
func homeDir() (home string, err error) {
home = os.Getenv("GORE_HOME")
if home != "" {
return
}
home, err = os.UserHomeDir()
if err != nil {
return
}
home = filepath.Join(home, ".gore")
return
}