2023-02-26 09:19:27 +01:00
|
|
|
package watcher
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"log"
|
|
|
|
|
|
|
|
pkgwatcher "gitea.urkob.com/urko/git-webhook-ci/pkg/watcher"
|
|
|
|
"github.com/fsnotify/fsnotify"
|
|
|
|
)
|
|
|
|
|
|
|
|
type watcher struct {
|
|
|
|
fswatcher *fsnotify.Watcher
|
|
|
|
deploy pkgwatcher.DeployFunc
|
|
|
|
}
|
|
|
|
|
2023-02-26 16:59:20 +01:00
|
|
|
type notifier struct{}
|
|
|
|
|
|
|
|
func (n *notifier) NewWatcher() (*fsnotify.Watcher, error) {
|
|
|
|
return fsnotify.NewWatcher()
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewNotifier() *notifier {
|
|
|
|
return ¬ifier{}
|
|
|
|
}
|
|
|
|
|
2023-02-26 10:58:55 +01:00
|
|
|
var (
|
|
|
|
errEventsClosedChan = errors.New("events is closed")
|
|
|
|
errErrorsClosedChan = errors.New("errors is closed")
|
|
|
|
)
|
|
|
|
|
2023-02-26 16:59:20 +01:00
|
|
|
func NewWatcher(notifier pkgwatcher.NotifyIface, deploy pkgwatcher.DeployFunc) *watcher {
|
|
|
|
wt, err := notifier.NewWatcher()
|
2023-02-26 09:19:27 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("fsnotify.NewWatcher: %s\n", err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return &watcher{
|
|
|
|
fswatcher: wt,
|
|
|
|
deploy: deploy,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *watcher) Monitor(path string) error {
|
|
|
|
return w.fswatcher.Add(path)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start listening for events.
|
|
|
|
func (w *watcher) Listen(binaryPath, scriptPath string, outputErr chan<- error) {
|
|
|
|
go func(events chan fsnotify.Event, errChan chan error, outputErr chan<- error) {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case event, ok := <-events:
|
|
|
|
if !ok {
|
2023-02-26 10:58:55 +01:00
|
|
|
log.Println(errEventsClosedChan)
|
|
|
|
outputErr <- errEventsClosedChan
|
2023-02-26 09:19:27 +01:00
|
|
|
return
|
|
|
|
}
|
2023-02-26 16:26:13 +01:00
|
|
|
|
2023-02-26 09:19:27 +01:00
|
|
|
if !event.Has(fsnotify.Write) {
|
|
|
|
log.Printf("is not Write: %s\n", event.Name)
|
|
|
|
continue
|
|
|
|
}
|
2023-02-26 16:26:13 +01:00
|
|
|
log.Printf("event: %s | op: %s \n", event.Name, event.Op)
|
2023-02-26 09:19:27 +01:00
|
|
|
|
|
|
|
if err := w.deploy(binaryPath, scriptPath); err != nil {
|
|
|
|
log.Printf("deploy: %s\n", err)
|
2023-02-26 10:58:55 +01:00
|
|
|
outputErr <- err
|
2023-02-26 09:19:27 +01:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
case err, ok := <-errChan:
|
|
|
|
if !ok {
|
2023-02-26 10:58:55 +01:00
|
|
|
log.Println(errErrorsClosedChan)
|
|
|
|
outputErr <- errErrorsClosedChan
|
2023-02-26 09:19:27 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Printf("<-errors: %s\n", err)
|
2023-02-26 10:58:55 +01:00
|
|
|
outputErr <- err
|
2023-02-26 09:19:27 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}(w.fswatcher.Events, w.fswatcher.Errors, outputErr)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *watcher) Close() error {
|
|
|
|
return w.fswatcher.Close()
|
|
|
|
}
|