history.go
This file
The walk stopped after 200 commits: lines older than 76efddd point at it.
bash: shift-delete to delete history entries during CTRL-RJunegunn Choibefore adoption76efddd
lines 1–95why, one step back1package fzf23import (4 "errors"5 "os"6 "strings"7)89// History struct represents input history10type History struct {11 path string12 lines []string13 modified map[int]string14 maxSize int15 cursor int16}1718// NewHistory returns the pointer to a new History struct19func 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 }2627 // Read history file28 data, err := os.ReadFile(path)29 if err != nil {30 // If it doesn't exist, check if we can create a file with the name31 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 lines41 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}, nil51}5253func (h *History) append(line string) error {54 // We don't append empty lines55 if len(line) == 0 {56 return nil57 }5859 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}6667func (h *History) override(str string) {68 // You can update the history, but they're not written to the file69 if h.cursor == len(h.lines)-1 {70 h.lines[h.cursor] = str71 } else if h.cursor < len(h.lines)-1 {72 h.modified[h.cursor] = str73 }74}7576func (h *History) current() string {77 if str, prs := h.modified[h.cursor]; prs {78 return str79 }80 return h.lines[h.cursor]81}8283func (h *History) previous() string {84 if h.cursor > 0 {85 h.cursor--86 }87 return h.current()88}8990func (h *History) next() string {91 if h.cursor < len(h.lines)-1 {92 h.cursor++93 }94 return h.current()95}