feat: add file history (closes #97)

windows-fixes
TorchedSammy 2022-03-04 21:55:37 -04:00
parent 6b9bbb615d
commit f26ef935dd
Signed by: sammyette
GPG Key ID: 904FC49417B44DCD
2 changed files with 72 additions and 0 deletions

67
history.go 100644
View File

@ -0,0 +1,67 @@
package main
import (
"errors"
"io/fs"
"os"
"strings"
)
type fileHistory struct {
items []string
f *os.File
}
func newFileHistory() (*fileHistory, error) {
data, err := os.ReadFile(defaultHistPath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
}
var itms []string
for _, l := range strings.Split(string(data), "\n") {
itms = append(itms, l)
}
f, err := os.OpenFile(defaultHistPath, os.O_RDWR | os.O_CREATE, 0755)
if err != nil {
return nil, err
}
fh := &fileHistory{
items: itms,
f: f,
}
return fh, nil
}
func (h *fileHistory) Write(line string) (int, error) {
_, err := h.f.WriteString(line + "\n")
if err != nil {
return 0, err
}
h.f.Sync()
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 nil
}

5
rl.go
View File

@ -18,6 +18,11 @@ type lineReader struct {
// other gophers might hate this naming but this is local, shut up // other gophers might hate this naming but this is local, shut up
func newLineReader(prompt string) *lineReader { func newLineReader(prompt string) *lineReader {
rl := readline.NewInstance() rl := readline.NewInstance()
fileHist, err := newFileHistory()
if err != nil {
panic(err)
}
rl.SetHistoryCtrlR("file", fileHist)
rl.ShowVimMode = false rl.ShowVimMode = false
rl.ViModeCallback = func(mode readline.ViMode) { rl.ViModeCallback = func(mode readline.ViMode) {
modeStr := "" modeStr := ""