clipman/storer.go

67 lines
1.4 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
2019-09-17 09:46:30 +02:00
"fmt"
"io/ioutil"
"log"
"os/exec"
)
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-17 09:46:30 +02:00
// drop oldest items that exceed max list size
if 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 {
if err := exec.Command("wl-copy", []string{"--", text}...).Run(); err != nil {
2019-09-17 09:46:30 +02:00
log.Printf("Error running wl-copy: %s", 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)
}