You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
826 B
53 lines
826 B
4 years ago
|
package lock
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"path"
|
||
|
"sync"
|
||
|
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
var lock *viper.Viper
|
||
|
var file string
|
||
|
var once sync.Once
|
||
|
|
||
|
func getLock() *viper.Viper {
|
||
|
if lock == nil {
|
||
|
|
||
|
once.Do(func() {
|
||
|
lock = viper.New()
|
||
|
lock.SetDefault("running", false)
|
||
|
p := path.Dir(viper.ConfigFileUsed())
|
||
|
file = path.Join(p, ".autorestic.lock.yml")
|
||
|
lock.SetConfigFile(file)
|
||
|
lock.SetConfigType("yml")
|
||
|
lock.ReadInConfig()
|
||
|
})
|
||
|
}
|
||
|
return lock
|
||
|
}
|
||
|
|
||
|
func set(locked bool) error {
|
||
|
lock := getLock()
|
||
|
if locked {
|
||
|
running := lock.GetBool("running")
|
||
|
if running {
|
||
|
return errors.New("an instance is already running")
|
||
|
}
|
||
|
}
|
||
|
lock.Set("running", locked)
|
||
|
if err := lock.WriteConfigAs(file); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func Lock() error {
|
||
|
return set(true)
|
||
|
}
|
||
|
|
||
|
func Unlock() error {
|
||
|
return set(false)
|
||
|
}
|