This repository has been archived on 2021-07-08. You can view files and clone it, but cannot push or open issues or pull requests.
opensend/config.go

67 lines
1.6 KiB
Go
Raw Normal View History

2020-12-03 10:12:43 +00:00
package main
import (
2020-12-31 07:54:18 +00:00
"errors"
"github.com/pelletier/go-toml"
2020-12-03 10:12:43 +00:00
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"io/ioutil"
"os"
)
type Config struct {
2020-12-31 07:54:18 +00:00
Receiver ReceiverConfig
Sender SenderConfig
Targets map[string]map[string]string
2020-12-03 10:12:43 +00:00
}
2020-12-31 07:54:18 +00:00
type ReceiverConfig struct {
DestDir string `toml:"destinationDirectory"`
SkipZeroconf bool
WorkDir string `toml:"workingDirectory"`
2020-12-03 10:12:43 +00:00
}
2020-12-31 07:54:18 +00:00
type SenderConfig struct {
WorkDir string `toml:"workingDirectory"`
}
2020-12-31 07:54:18 +00:00
func GetConfigPath() string {
2020-12-03 10:12:43 +00:00
// Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
2020-12-31 07:54:18 +00:00
configLocations := []string{"~/.config/opensend.toml", "/etc/opensend.toml"}
for _, configLocation := range configLocations {
expandedPath := ExpandPath(configLocation)
if _, err := os.Stat(expandedPath); errors.Is(err, os.ErrNotExist) {
continue
}
return expandedPath
2020-12-21 07:18:42 +00:00
}
2020-12-31 07:54:18 +00:00
return ""
2020-12-03 10:12:43 +00:00
}
2020-12-31 07:54:18 +00:00
func NewConfig(path string) *Config {
2020-12-03 10:12:43 +00:00
// Use ConsoleWriter logger
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr}).Hook(FatalHook{})
2020-12-31 07:54:18 +00:00
newConfig := &Config{}
newConfig.SetDefaults()
if path != "" {
confData, err := ioutil.ReadFile(path)
2020-12-21 07:18:42 +00:00
if err != nil {
2020-12-31 07:54:18 +00:00
log.Fatal().Err(err).Msg("Error reading config")
2020-12-21 07:18:42 +00:00
}
2020-12-31 07:54:18 +00:00
err = toml.Unmarshal(confData, newConfig)
2020-12-21 07:18:42 +00:00
if err != nil {
2020-12-31 07:54:18 +00:00
log.Fatal().Err(err).Msg("Error unmarshalling toml")
2020-12-21 07:18:42 +00:00
}
}
2020-12-31 07:54:18 +00:00
return newConfig
2020-12-03 10:12:43 +00:00
}
2020-12-31 07:54:18 +00:00
func (config *Config) SetDefaults() {
config.Receiver.DestDir = ExpandPath("~/Downloads")
config.Receiver.WorkDir = ExpandPath("~/.opensend")
config.Receiver.SkipZeroconf = false
config.Sender.WorkDir = ExpandPath("~/.opensend")
config.Targets = map[string]map[string]string{}
2020-12-21 07:18:42 +00:00
}