package emulator import ( "bufio" "fmt" "os" ) type commandHistory struct { file *os.File history []string } // Create new commandHistory struct. // Opens specified file and reads its contents into a string array func newCommandHistory(filepath string) (commandHistory, error) { f, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) if err != nil { return commandHistory{}, fmt.Errorf("could not open file") } ch := commandHistory{file: f, history: []string{}} err = ch.readFromFile() if err != nil { return commandHistory{}, fmt.Errorf("error reading from file") } return ch, nil } func (ch *commandHistory) readFromFile() error { scanner := bufio.NewScanner(ch.file) for scanner.Scan() { ch.history = append(ch.history, scanner.Text()) } return scanner.Err() } // Update both history and file with new input func (ch *commandHistory) updateHistory(in string, limit int) error { if len(ch.history) == 0 || in != ch.history[len(ch.history)-1] { ch.history = append(ch.history, in) // Truncate ch.history to only the most recent commands within size limit if len(ch.history) > limit { diff := len(ch.history) - limit ch.history = ch.history[diff:] } // Write new line to file _, err := ch.file.WriteString(in + "\n") if err != nil { return err } } return nil } func (ch *commandHistory) close() { ch.file.Close() }