From 31b3e2a8ad9a74b9bfbfe7d7d740b64df0472d55 Mon Sep 17 00:00:00 2001 From: Gadzhi Kharkharov Date: Wed, 15 Sep 2021 15:48:42 +0300 Subject: [PATCH] close fsnotify watcher and cleanup tmp files immediately after reading --- kak/get.go | 11 +++++++---- kak/tmp.go | 13 ++++++++----- 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/kak/get.go b/kak/get.go index b1affa8..f97eb7e 100644 --- a/kak/get.go +++ b/kak/get.go @@ -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 } @@ -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 } diff --git a/kak/tmp.go b/kak/tmp.go index 74dabc2..9e36709 100644 --- a/kak/tmp.go +++ b/kak/tmp.go @@ -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 { @@ -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) } @@ -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 {