diff options
Diffstat (limited to 'pkg')
-rw-r--r-- | pkg/atexit/atexit.go | 13 | ||||
-rw-r--r-- | pkg/try/try.go | 19 | ||||
-rw-r--r-- | pkg/watch/watch.go | 41 |
3 files changed, 73 insertions, 0 deletions
diff --git a/pkg/atexit/atexit.go b/pkg/atexit/atexit.go new file mode 100644 index 0000000..a349649 --- /dev/null +++ b/pkg/atexit/atexit.go @@ -0,0 +1,13 @@ +package atexit + +var hooks = []func(){} + +func Register(f func()) { + hooks = append(hooks, f) +} + +func Exec() { + for i := len(hooks) - 1; i >= 0; i-- { + hooks[i]() + } +} diff --git a/pkg/try/try.go b/pkg/try/try.go new file mode 100644 index 0000000..2576dcd --- /dev/null +++ b/pkg/try/try.go @@ -0,0 +1,19 @@ +package try + +import ( + "log" + + "git.thomasvoss.com/euro-cash.eu/pkg/atexit" +) + +func Try(e error) { + if e != nil { + atexit.Exec() + log.Fatalln(e) + } +} + +func Try2[T any](x T, e error) T { + Try(e) + return x +} diff --git a/pkg/watch/watch.go b/pkg/watch/watch.go new file mode 100644 index 0000000..f409dac --- /dev/null +++ b/pkg/watch/watch.go @@ -0,0 +1,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) + } +} |