-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
sample_updater.go
66 lines (57 loc) · 1.76 KB
/
sample_updater.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
package bot
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
// SampleUpdater represents a file that can be read and appended to.
// this is a helper for dynamic reloading of samples used by SpamFilter
type SampleUpdater struct {
fileName string
}
// NewSampleUpdater creates a new SampleUpdater
func NewSampleUpdater(fileName string) *SampleUpdater {
return &SampleUpdater{fileName: fileName}
}
// Reader returns a reader for the file, caller must close it
func (s *SampleUpdater) Reader() (io.ReadCloser, error) {
fh, err := os.Open(s.fileName)
if err != nil {
return nil, fmt.Errorf("failed to open %s: %w", s.fileName, err)
}
return fh, nil
}
// Append a message to the file, preventing duplicates
func (s *SampleUpdater) Append(msg string) error {
// if file does not exist, create it
if _, err := os.Stat(s.fileName); os.IsNotExist(err) {
if _, err = os.Create(s.fileName); err != nil {
return fmt.Errorf("failed to create %s: %w", s.fileName, err)
}
}
// check if the message is already in the file
fh, err := os.Open(s.fileName)
if err != nil {
return fmt.Errorf("failed to open %s: %w", s.fileName, err)
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
for scanner.Scan() {
// if a line matches the message, return right away
if strings.EqualFold(strings.TrimSpace(scanner.Text()), strings.TrimSpace(msg)) {
return nil
}
}
// append the message to the file
fh, err = os.OpenFile(s.fileName, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644) //nolint:gosec // keep it readable by all
if err != nil {
return fmt.Errorf("failed to open %s: %w", s.fileName, err)
}
defer fh.Close()
if _, err = fh.WriteString(strings.ReplaceAll(msg, "\n", " ") + "\n"); err != nil {
return fmt.Errorf("failed to write to %s: %w", s.fileName, err)
}
return nil
}