diff --git a/events/go.mod b/events/go.mod new file mode 100644 index 0000000..ec36a11 --- /dev/null +++ b/events/go.mod @@ -0,0 +1,5 @@ +module gitea.codeblob.work/pk/gut/events + +go 1.22.0 + +require github.com/google/uuid v1.6.0 diff --git a/events/go.sum b/events/go.sum new file mode 100644 index 0000000..7790d7c --- /dev/null +++ b/events/go.sum @@ -0,0 +1,2 @@ +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= diff --git a/events/simple_emitter.go b/events/simple_emitter.go new file mode 100644 index 0000000..4ea9011 --- /dev/null +++ b/events/simple_emitter.go @@ -0,0 +1,56 @@ +package events + +import ( + "sync" + + "github.com/google/uuid" +) + +type syncEventListener struct { + id string + cb func(event string, data any) +} + +type SyncEmitter struct { + sync.Mutex + listeners map[string][]syncEventListener +} + +func NewSyncEventListener(cb func(event string, data any)) *syncEventListener { + return &syncEventListener{ + id: uuid.NewString(), + cb: cb, + } +} + +func NewSyncEmitter() *SyncEmitter { + return &SyncEmitter{ + listeners: make(map[string][]syncEventListener), + } +} + +func (e *SyncEmitter) Emit(event string, data any) { + e.Lock() + defer e.Unlock() + targets := e.listeners[event] + + for _, listener := range targets { + listener.cb(event, data) + } +} + +func (e *SyncEmitter) AddListener(event string, listener syncEventListener) { + e.Lock() + defer e.Unlock() + e.listeners[event] = append(e.listeners[event], listener) +} + +func (e *SyncEmitter) RemoveListener(event string, listener syncEventListener) { + e.Lock() + defer e.Unlock() + for i, l := range e.listeners[event] { + if l.id == listener.id { + e.listeners[event] = append(e.listeners[event][:i], e.listeners[event][i+1:]...) + } + } +} diff --git a/fs/file.go b/fs/file.go new file mode 100644 index 0000000..e629749 --- /dev/null +++ b/fs/file.go @@ -0,0 +1,11 @@ +package fs + +import ( + "errors" + "os" +) + +func PathExists(path string) bool { + _, err := os.Stat(path) + return !errors.Is(err, os.ErrNotExist) +} diff --git a/fs/go.mod b/fs/go.mod new file mode 100644 index 0000000..5d2068b --- /dev/null +++ b/fs/go.mod @@ -0,0 +1,3 @@ +module gitea.codeblob.work/pk/gut/fs + +go 1.22.0