...
1 package emulator
2
3 import (
4 "bufio"
5 "fmt"
6 "os"
7 )
8
9 type commandHistory struct {
10 file *os.File
11 history []string
12 }
13
14
15
16 func newCommandHistory(filepath string) (commandHistory, error) {
17 f, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
18 if err != nil {
19 return commandHistory{}, fmt.Errorf("could not open file")
20 }
21 ch := commandHistory{file: f, history: []string{}}
22 err = ch.readFromFile()
23 if err != nil {
24 return commandHistory{}, fmt.Errorf("error reading from file")
25 }
26 return ch, nil
27 }
28
29 func (ch *commandHistory) readFromFile() error {
30 scanner := bufio.NewScanner(ch.file)
31 for scanner.Scan() {
32 ch.history = append(ch.history, scanner.Text())
33 }
34 return scanner.Err()
35 }
36
37
38 func (ch *commandHistory) updateHistory(in string, limit int) error {
39 if len(ch.history) == 0 || in != ch.history[len(ch.history)-1] {
40 ch.history = append(ch.history, in)
41
42 if len(ch.history) > limit {
43 diff := len(ch.history) - limit
44 ch.history = ch.history[diff:]
45 }
46
47 _, err := ch.file.WriteString(in + "\n")
48 if err != nil {
49 return err
50 }
51 }
52 return nil
53 }
54
55 func (ch *commandHistory) close() {
56 ch.file.Close()
57 }
58
View as plain text