-
Notifications
You must be signed in to change notification settings - Fork 46
/
storer.go
70 lines (57 loc) · 1.5 KB
/
storer.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
)
func store(text string, history []string, histfile string, max int, persist bool) error {
if text == "" {
return nil
}
l := len(history)
if l > 0 {
// this avoids entering an endless loop,
// see https://github.com/bugaevc/wl-clipboard/issues/65
last := history[l-1]
if text == last {
return nil
}
// drop oldest items that exceed max list size
// if max = 0, we allow infinite history; NOTE: users should NOT rely on this behaviour as we might change it without notice
if max != 0 && l >= max {
// usually just one item, but more if we suddenly reduce our --max-items
history = history[l-max+1:]
}
// remove duplicates
history = filter(history, text)
}
history = append(history, text)
// dump history to file so that other apps can query it
if err := write(history, histfile); err != nil {
return fmt.Errorf("error writing history: %s", err)
}
// make the copy buffer available to all applications,
// even when the source has disappeared
if persist {
serveTxt(text)
}
return nil
}
// filter removes all occurrences of text
func filter(slice []string, text string) []string {
var filtered []string
for _, s := range slice {
if s != text {
filtered = append(filtered, s)
}
}
return filtered
}
// write dumps history to json file
func write(history []string, histfile string) error {
b, err := json.Marshal(history)
if err != nil {
return err
}
return ioutil.WriteFile(histfile, b, 0644)
}