Skip to content

Commit

Permalink
close fsnotify watcher and cleanup tmp files immediately after reading
Browse files Browse the repository at this point in the history
  • Loading branch information
kkga committed Sep 15, 2021
1 parent 086d7e7 commit 31b3e2a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
11 changes: 7 additions & 4 deletions kak/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@ package kak

import (
"fmt"
"io/ioutil"
"os"
"strings"
)

func Get(kctx *Context, query string) ([]string, error) {
// create a tmp file for kak to echo the value
f, err := os.CreateTemp("", "kks-tmp")
tmp, err := ioutil.TempFile("", "kks-tmp")
if err != nil {
return nil, err
}

// kak will output to file, so we create a chan for reading
ch := make(chan string)
go ReadTmp(f, ch)
go ReadTmp(tmp, ch)

// tell kak to echo the requested state
sendCmd := fmt.Sprintf("echo -quoting kakoune -to-file %s %%{ %s }", f.Name(), query)
sendCmd := fmt.Sprintf("echo -quoting kakoune -to-file %s %%{ %s }", tmp.Name(), query)
if err := Send(kctx, sendCmd); err != nil {
return nil, err
}
Expand All @@ -32,6 +33,8 @@ func Get(kctx *Context, query string) ([]string, error) {
outStrs[i] = strings.Trim(val, "''")
}

f.Close()
tmp.Close()
os.Remove(tmp.Name())

return outStrs, nil
}
13 changes: 8 additions & 5 deletions kak/tmp.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package kak

import (
"io/ioutil"
"log"
"os"

"github.com/fsnotify/fsnotify"
)

func ReadTmp(f *os.File, c chan string) {
func ReadTmp(tmp *os.File, c chan string) {
// create a watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
Expand All @@ -16,7 +17,7 @@ func ReadTmp(f *os.File, c chan string) {
defer watcher.Close()

// add file to watch
err = watcher.Add(f.Name())
err = watcher.Add(tmp.Name())
if err != nil {
log.Fatal(err)
}
Expand All @@ -28,14 +29,16 @@ func ReadTmp(f *os.File, c chan string) {
if !ok {
return
}
// if file written, read it and send to chan
// if file written, read it, send to chan and close/clean
if event.Op&fsnotify.Write == fsnotify.Write {
dat, err := os.ReadFile(f.Name())
defer os.Remove(f.Name())
dat, err := ioutil.ReadFile(tmp.Name())
if err != nil {
log.Fatal(err)
}
c <- string(dat)
watcher.Close()
tmp.Close()
os.Remove(tmp.Name())
}
case err, ok := <-watcher.Errors:
if !ok {
Expand Down

0 comments on commit 31b3e2a

Please sign in to comment.