summaryrefslogtreecommitdiffhomepage
path: root/pkg/watch/watch.go
blob: f409dac3c26dae4558566eef3087fcd457e8eac4 (plain) (blame)
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
package watch

import (
	"errors"
	"io/fs"
	"log"
	"os"
	"time"

	. "git.thomasvoss.com/euro-cash.eu/pkg/try"
)

func File(path string, f func()) {
	impl(path, os.Stat, f)
}

func FileFS(dir fs.FS, path string, f func()) {
	impl(path, func(path string) (os.FileInfo, error) {
		return fs.Stat(dir, path)
	}, f)
}

func impl(path string, statfn func(string) (os.FileInfo, error), f func()) {
	ostat := Try2(statfn(path))

	for {
		nstat, err := statfn(path)
		switch {
		case errors.Is(err, os.ErrNotExist):
			return
		case err != nil:
			log.Println(err)
		}

		if nstat.ModTime() != ostat.ModTime() {
			f()
			ostat = nstat
		}
		time.Sleep(1 * time.Second)
	}
}