-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
cmd.go
101 lines (79 loc) · 1.71 KB
/
cmd.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
package repl
import (
"fmt"
"os"
"strings"
"google.golang.org/protobuf/proto"
)
const HISTORY_LIMIT = 100
func (r *Repl) init() error {
r.mu.Lock()
defer r.mu.Unlock()
path := fmt.Sprintf("%s/repl.history", os.TempDir())
// create file if not exist
file, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, os.ModePerm) // #nosec
if err != nil {
return err
}
defer func() {
_ = file.Close() // #nosec
}()
// read file
payload, err := os.ReadFile(path) // #nosec
if err != nil {
return err
}
if len(payload) != 0 {
err = proto.Unmarshal(payload, r.session)
if err != nil {
return err
}
}
return nil
}
func (r *Repl) help() {
fmt.Printf(`
ShortDB repl
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open DATABASENAME" to reopen on a persistent database.
current database: %s
`, r.session.GetCurrentDatabase())
}
func (r *Repl) save() error {
return r.engine.Close()
}
func (r *Repl) close() error {
r.mu.Lock()
defer r.mu.Unlock()
path := fmt.Sprintf("%s/repl.history", os.TempDir())
// create file if not exist
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, os.ModePerm) // #nosec
if err != nil {
return err
}
defer func() {
_ = file.Close() // #nosec
}()
// Save last 100 record
if len(r.session.GetHistory()) > HISTORY_LIMIT {
r.session.History = r.session.GetHistory()[HISTORY_LIMIT:]
}
payload, err := proto.Marshal(r.session)
if err != nil {
return err
}
_, err = file.Write(payload)
if err != nil {
return err
}
return nil
}
func (r *Repl) open(t string) error {
s := strings.Split(t, " ")
if len(s) != 2 { //nolint:mnd,goerr113 // ignore
return ErrStatus
}
r.session.CurrentDatabase = s[1]
return nil
}