Hilbish/history.go

81 lines
1.2 KiB
Go
Raw Normal View History

2022-03-05 01:55:37 +00:00
package main
import (
"errors"
"io/fs"
"os"
"strings"
)
type fileHistory struct {
items []string
f *os.File
}
func newFileHistory() *fileHistory {
err := os.MkdirAll(defaultHistDir, 0755)
if err != nil {
panic(err)
}
2022-03-05 01:55:37 +00:00
data, err := os.ReadFile(defaultHistPath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
panic(err)
2022-03-05 01:55:37 +00:00
}
}
2022-03-05 19:23:17 +00:00
itms := []string{""}
lines := strings.Split(string(data), "\n")
for i, l := range lines {
if i == len(lines) - 1 {
continue
}
2022-03-05 01:55:37 +00:00
itms = append(itms, l)
}
f, err := os.OpenFile(defaultHistPath, os.O_APPEND | os.O_WRONLY | os.O_CREATE, 0755)
2022-03-05 01:55:37 +00:00
if err != nil {
panic(err)
2022-03-05 01:55:37 +00:00
}
2022-03-05 19:23:17 +00:00
2022-03-05 01:55:37 +00:00
fh := &fileHistory{
items: itms,
f: f,
}
2022-03-05 19:23:17 +00:00
return fh
2022-03-05 01:55:37 +00:00
}
func (h *fileHistory) Write(line string) (int, error) {
if line == "" {
return len(h.items), nil
}
2022-03-05 01:55:37 +00:00
_, err := h.f.WriteString(line + "\n")
if err != nil {
return 0, err
}
h.f.Sync()
2022-03-05 19:23:17 +00:00
2022-03-05 01:55:37 +00:00
h.items = append(h.items, line)
return len(h.items), nil
}
func (h *fileHistory) GetLine(idx int) (string, error) {
if len(h.items) == 0 {
return "", nil
}
if idx == -1 { // this should be fixed readline side
return "", nil
}
return h.items[idx], nil
}
func (h *fileHistory) Len() int {
return len(h.items)
}
func (h *fileHistory) Dump() interface{} {
return h.items
2022-03-05 01:55:37 +00:00
}