72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
|
package config
|
||
|
|
||
|
import (
|
||
|
"os"
|
||
|
"path"
|
||
|
"velvettear/worklog/internal/log"
|
||
|
"velvettear/worklog/internal/tools"
|
||
|
|
||
|
"github.com/spf13/viper"
|
||
|
)
|
||
|
|
||
|
// exported function(s)
|
||
|
func Initialize() {
|
||
|
timestamp := tools.LogTimestamp()
|
||
|
configSpecified := false
|
||
|
for index, arg := range os.Args {
|
||
|
if arg == "-h" || arg == "--"+help {
|
||
|
tools.PrintHelp()
|
||
|
}
|
||
|
if arg == "-c" || arg == "--"+config {
|
||
|
viper.SetConfigFile(os.Args[index+1])
|
||
|
configSpecified = true
|
||
|
}
|
||
|
}
|
||
|
setDefaults()
|
||
|
if !configSpecified {
|
||
|
viper.SetConfigName("config")
|
||
|
viper.SetConfigType("yaml")
|
||
|
viper.AddConfigPath("$HOME/.config/worklog/")
|
||
|
workingDirectory, error := os.Getwd()
|
||
|
for error == nil && path.Base(workingDirectory) != "worklog" {
|
||
|
workingDirectory = path.Dir(workingDirectory)
|
||
|
if workingDirectory == "/" {
|
||
|
workingDirectory = "."
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
viper.AddConfigPath(workingDirectory)
|
||
|
}
|
||
|
error := viper.ReadInConfig()
|
||
|
if configSpecified && error != nil {
|
||
|
log.FatalTimed("encountered an error parsing specified config file '"+viper.ConfigFileUsed()+"'", timestamp, error.Error())
|
||
|
}
|
||
|
headers := viper.GetStringSlice(reportHeaders)
|
||
|
headersLength := len(headers)
|
||
|
defaultLength := len(tools.ReportHeaders)
|
||
|
for headersLength < defaultLength {
|
||
|
tmp := tools.ReportHeaders[headersLength]
|
||
|
headers = append(headers, tmp)
|
||
|
headersLength = len(headers)
|
||
|
}
|
||
|
viper.Set(reportHeaders, headers)
|
||
|
if Debug() {
|
||
|
log.SetLogLevel(0)
|
||
|
}
|
||
|
log.DebugTimed("parsed config file '"+viper.ConfigFileUsed()+"'", timestamp)
|
||
|
}
|
||
|
|
||
|
func setDefaults() {
|
||
|
home := path.Join(os.TempDir(), "worklog")
|
||
|
// set database defaults
|
||
|
viper.SetDefault(database, path.Join(home, "worklog.sqlite"))
|
||
|
// set server defaults
|
||
|
viper.SetDefault(serverListen, "localhost")
|
||
|
viper.SetDefault(serverPort, 3333)
|
||
|
// set report defaults
|
||
|
viper.SetDefault(reportHeaders, tools.ReportHeaders)
|
||
|
// set other defaults
|
||
|
viper.SetDefault(debug, false)
|
||
|
viper.SetDefault(help, false)
|
||
|
}
|