futriis/internal/cli/history.go

86 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// /futriis/internal/cli/history.go
// Пакет cli реализует управление историей команд с поддержкой клавиши Up
package cli
import (
"os"
"golang.org/x/term"
)
// History управляет историей команд
type History struct {
commands []string
position int
maxSize int
}
// NewHistory создаёт новую историю команд
func NewHistory(maxSize int) *History {
return &History{
commands: make([]string, 0, maxSize),
position: 0,
maxSize: maxSize,
}
}
// Add добавляет команду в историю
func (h *History) Add(cmd string) {
if cmd == "" {
return
}
// Не добавляем дубликаты подряд
if len(h.commands) > 0 && h.commands[len(h.commands)-1] == cmd {
return
}
// Если достигнут максимум, удаляем самую старую команду
if len(h.commands) >= h.maxSize {
h.commands = h.commands[1:]
}
h.commands = append(h.commands, cmd)
h.position = len(h.commands)
}
// GetPrevious возвращает предыдущую команду из истории
func (h *History) GetPrevious() string {
if len(h.commands) == 0 {
return ""
}
if h.position > 0 {
h.position--
}
return h.commands[h.position]
}
// GetNext возвращает следующую команду из истории
func (h *History) GetNext() string {
if h.position < len(h.commands)-1 {
h.position++
return h.commands[h.position]
}
h.position = len(h.commands)
return ""
}
// Reset сбрасывает позицию в истории
func (h *History) Reset() {
h.position = len(h.commands)
}
// SetupRawMode устанавливает терминал в raw-режим для обработки клавиш
func SetupRawMode() (*term.State, error) {
fd := int(os.Stdin.Fd())
return term.MakeRaw(fd)
}
// RestoreMode восстанавливает режим терминала
func RestoreMode(oldState *term.State) error {
fd := int(os.Stdin.Fd())
return term.Restore(fd, oldState)
}