| 1 |
package fzf |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"os" |
| 6 |
"strings" |
| 7 |
) |
| 8 |
|
| 9 |
// History struct represents input history |
| 10 |
type History struct { |
| 11 |
path string |
| 12 |
lines []string |
| 13 |
modified map[int]string |
| 14 |
maxSize int |
| 15 |
cursor int |
| 16 |
} |
| 17 |
|
| 18 |
// NewHistory returns the pointer to a new History struct |
| 19 |
func NewHistory(path string, maxSize int) (*History, error) { |
| 20 |
fmtError := func(e error) error { |
| 21 |
if os.IsPermission(e) { |
| 22 |
return errors.New("permission denied: " + path) |
| 23 |
} |
| 24 |
return errors.New("invalid history file: " + e.Error()) |
| 25 |
} |
| 26 |
|
| 27 |
// Read history file |
| 28 |
data, err := os.ReadFile(path) |
| 29 |
if err != nil { |
| 30 |
// If it doesn't exist, check if we can create a file with the name |
| 31 |
if os.IsNotExist(err) { |
| 32 |
data = []byte{} |
| 33 |
if err := os.WriteFile(path, data, 0600); err != nil { |
| 34 |
return nil, fmtError(err) |
| 35 |
} |
| 36 |
} else { |
| 37 |
return nil, fmtError(err) |
| 38 |
} |
| 39 |
} |
| 40 |
// Split lines and limit the maximum number of lines |
| 41 |
lines := strings.Split(strings.Trim(string(data), "\n"), "\n") |
| 42 |
if len(lines[len(lines)-1]) > 0 { |
| 43 |
lines = append(lines, "") |
| 44 |
} |
| 45 |
return &History{ |
| 46 |
path: path, |
| 47 |
maxSize: maxSize, |
| 48 |
lines: lines, |
| 49 |
modified: make(map[int]string), |
| 50 |
cursor: len(lines) - 1}, nil |
| 51 |
} |
| 52 |
|
| 53 |
func (h *History) append(line string) error { |
| 54 |
// We don't append empty lines |
| 55 |
if len(line) == 0 { |
| 56 |
return nil |
| 57 |
} |
| 58 |
|
| 59 |
lines := append(h.lines[:len(h.lines)-1], line) |
| 60 |
if len(lines) > h.maxSize { |
| 61 |
lines = lines[len(lines)-h.maxSize:] |
| 62 |
} |
| 63 |
h.lines = append(lines, "") |
| 64 |
return os.WriteFile(h.path, []byte(strings.Join(h.lines, "\n")), 0600) |
| 65 |
} |
| 66 |
|
| 67 |
func (h *History) override(str string) { |
| 68 |
// You can update the history, but they're not written to the file |
| 69 |
if h.cursor == len(h.lines)-1 { |
| 70 |
h.lines[h.cursor] = str |
| 71 |
} else if h.cursor < len(h.lines)-1 { |
| 72 |
h.modified[h.cursor] = str |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
func (h *History) current() string { |
| 77 |
if str, prs := h.modified[h.cursor]; prs { |
| 78 |
return str |
| 79 |
} |
| 80 |
return h.lines[h.cursor] |
| 81 |
} |
| 82 |
|
| 83 |
func (h *History) previous() string { |
| 84 |
if h.cursor > 0 { |
| 85 |
h.cursor-- |
| 86 |
} |
| 87 |
return h.current() |
| 88 |
} |
| 89 |
|
| 90 |
func (h *History) next() string { |
| 91 |
if h.cursor < len(h.lines)-1 { |
| 92 |
h.cursor++ |
| 93 |
} |
| 94 |
return h.current() |
| 95 |
} |