clipman/storer.go

74 lines
1.6 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
2019-09-17 09:46:30 +02:00
"fmt"
"io/ioutil"
"log"
)
2019-09-17 09:46:30 +02:00
func store(text string, history []string, histfile string, max int, persist bool) error {
2019-09-16 20:38:39 +02:00
if text == "" {
2019-09-17 09:46:30 +02:00
return nil
2019-09-16 20:38:39 +02:00
}
l := len(history)
if l > 0 {
2019-09-21 09:52:15 +02:00
// this avoids entering an endless loop,
// see https://github.com/bugaevc/wl-clipboard/issues/65
last := history[l-1]
if text == last {
return nil
}
2019-09-17 09:46:30 +02:00
// drop oldest items that exceed max list size
2019-10-27 13:59:04 +01:00
// 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 {
2019-09-17 09:46:30 +02:00
// 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 {
2019-09-17 09:46:30 +02:00
return fmt.Errorf("error writing history: %s", err)
}
2019-09-17 09:46:30 +02:00
// make the copy buffer available to all applications,
// even when the source has disappeared
if persist {
2019-10-27 21:53:27 +01:00
if err := serveTxt(text); err != nil {
log.Print(err) // don't abort, minor error
}
}
2019-09-17 09:46:30 +02:00
return nil
}
2019-09-17 09:46:30 +02:00
// 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)
}
}
2019-09-17 09:46:30 +02:00
return filtered
}
2019-09-17 09:46:30 +02:00
// write dumps history to json file
func write(history []string, histfile string) error {
2019-09-17 09:46:30 +02:00
b, err := json.Marshal(history)
if err != nil {
return err
}
2019-09-17 09:46:30 +02:00
return ioutil.WriteFile(histfile, b, 0644)
}