-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhistory.go
122 lines (100 loc) · 1.82 KB
/
history.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
package main
import (
"bufio"
"fmt"
"os"
"path"
"strings"
)
type history struct {
entries []string
pos int
size int
fn *string
}
func newHistory(size int, fn *string) *history {
h := history{
entries: make([]string, 0),
pos: -1,
fn: fn,
size: size,
}
return &h
}
func (h *history) load() {
if h.fn == nil {
return
}
f, err := os.Open(*h.fn)
if err != nil {
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
for n := 0; n < h.size && scanner.Scan(); n++ {
his.entries = append(his.entries, scanner.Text())
}
}
func (h *history) save() {
if h.fn == nil {
return
}
if err := os.MkdirAll(path.Dir(*h.fn), os.ModePerm); err != nil {
fmt.Println(err)
}
f, err := os.Create(*h.fn)
if err != nil {
fmt.Println(err)
}
defer f.Close()
f.WriteString(strings.Join(h.entries, "\n"))
}
func (h *history) append() {
if h.fn == nil {
return
}
if err := os.MkdirAll(path.Dir(*h.fn), os.ModePerm); err != nil {
logger.ch <- err.Error()
}
f, err := os.OpenFile(*h.fn, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0660)
if err != nil {
logger.ch <- err.Error()
} else {
defer f.Close()
s := his.entries[len(his.entries)-1]
if len(his.entries) > 1 {
f.WriteString(fmt.Sprintf("\n%s", s))
} else {
f.WriteString(s)
}
}
}
func (h *history) insert(s string) {
if len(s) > 0 && (len(h.entries) == 0 || strings.Compare(s, h.entries[0]) != 0) {
h.entries = append([]string{s}, h.entries...)
}
h.pos = -1
if len(his.entries) > his.size {
his.entries = his.entries[:his.size]
}
h.append()
}
func (h *history) prev() string {
n := len(h.entries)
if n == 0 {
return ""
}
if h.pos < n-1 {
h.pos++
}
return h.entries[h.pos]
}
func (h *history) next() string {
if h.pos >= 0 {
h.pos--
}
if h.pos == -1 {
return ""
}
return h.entries[h.pos]
}