2015-09-07 16:25:13 +03:00
package main
import (
2015-09-07 18:39:22 +03:00
"os"
"path/filepath"
"strings"
2015-09-24 18:16:13 +03:00
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"gopkg.in/fsnotify.v1"
2015-09-07 16:25:13 +03:00
)
type FileProvider struct {
2015-09-12 16:10:03 +03:00
Watch bool
2015-09-07 18:39:22 +03:00
Filename string
2015-09-07 16:25:13 +03:00
}
2015-10-01 13:04:25 +03:00
func ( provider * FileProvider ) Provide ( configurationChan chan <- configMessage ) error {
2015-09-07 16:25:13 +03:00
watcher , err := fsnotify . NewWatcher ( )
if err != nil {
2015-09-11 17:37:13 +03:00
log . Error ( "Error creating file watcher" , err )
2015-10-01 13:04:25 +03:00
return err
2015-09-07 16:25:13 +03:00
}
2015-09-07 18:39:22 +03:00
file , err := os . Open ( provider . Filename )
2015-09-07 16:25:13 +03:00
if err != nil {
2015-09-11 17:37:13 +03:00
log . Error ( "Error opening file" , err )
2015-10-01 13:04:25 +03:00
return err
2015-09-07 16:25:13 +03:00
}
2015-09-07 18:39:22 +03:00
defer file . Close ( )
2015-09-07 16:25:13 +03:00
2015-10-03 17:50:53 +03:00
if provider . Watch {
// Process events
go func ( ) {
defer watcher . Close ( )
for {
select {
case event := <- watcher . Events :
if strings . Contains ( event . Name , file . Name ( ) ) {
log . Debug ( "File event:" , event )
configuration := provider . LoadFileConfig ( file . Name ( ) )
if configuration != nil {
configurationChan <- configMessage { "file" , configuration }
}
2015-09-08 00:25:07 +03:00
}
2015-10-03 17:50:53 +03:00
case error := <- watcher . Errors :
log . Error ( "Watcher event error" , error )
2015-09-07 18:39:22 +03:00
}
2015-09-07 16:25:13 +03:00
}
2015-10-03 17:50:53 +03:00
} ( )
2015-09-07 19:10:33 +03:00
err = watcher . Add ( filepath . Dir ( file . Name ( ) ) )
2015-10-03 17:50:53 +03:00
if err != nil {
log . Error ( "Error adding file watcher" , err )
return err
}
2015-09-07 18:39:22 +03:00
}
2015-09-07 16:25:13 +03:00
2015-09-08 01:15:14 +03:00
configuration := provider . LoadFileConfig ( file . Name ( ) )
2015-09-22 07:16:21 +03:00
configurationChan <- configMessage { "file" , configuration }
2015-10-01 13:04:25 +03:00
return nil
2015-09-07 16:25:13 +03:00
}
2015-09-08 01:15:14 +03:00
func ( provider * FileProvider ) LoadFileConfig ( filename string ) * Configuration {
configuration := new ( Configuration )
if _ , err := toml . DecodeFile ( filename , configuration ) ; err != nil {
2015-09-11 17:37:13 +03:00
log . Error ( "Error reading file:" , err )
2015-09-07 16:25:13 +03:00
return nil
}
2015-09-08 01:15:14 +03:00
return configuration
2015-09-12 16:10:03 +03:00
}