-
Notifications
You must be signed in to change notification settings - Fork 4
/
history.go
118 lines (97 loc) · 2.49 KB
/
history.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// Copyright (C) 2021 Gregory Anders <greg@gpanders.com>
// Copyright (C) 2021 Herby Gillot <herby.gillot@gmail.com>
//
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
type history struct {
path string
Items []string
}
func (h *history) Init(path string) error {
h.path = path
filebytes, err := os.ReadFile(path)
if err != nil {
// If the history file doesn't exist, then
// return an empty history.
if errors.Is(err, os.ErrNotExist) {
return nil
} else {
return fmt.Errorf("error retrieving history: %w", err)
}
}
scanner := bufio.NewScanner(bytes.NewReader(filebytes))
for scanner.Scan() {
h.Items = append(h.Items, scanner.Text())
}
if err := scanner.Err(); err != nil {
return fmt.Errorf(
"error retrieving history: %w", err,
)
}
return nil
}
func (h *history) Add(expression string) error {
expression = strings.TrimSpace(expression)
if expression == "" {
return nil
}
if h.path == "" {
return nil
}
// Don't continue with adding the expression if it is saved in history
// already.
if contains(h.Items, expression) {
return nil
}
h.Items = append(h.Items, expression)
file, err := h.openFile()
if err != nil {
return fmt.Errorf("error opening history for writing: %w", err)
}
fmt.Fprintln(file, expression)
if err = file.Close(); err != nil {
return fmt.Errorf("error closing history file: %w", err)
}
return nil
}
func (h *history) openFile() (*os.File, error) {
err := os.MkdirAll(filepath.Dir(h.path), os.ModePerm)
if err != nil {
return nil, err
}
f, err := os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
return nil, err
}
return f, nil
}
func contains(arr []string, elem string) bool {
for _, v := range arr {
if elem == v {
return true
}
}
return false
}