wip: process management

This commit is contained in:
2023-08-31 08:05:20 +10:00
parent 9cbdbebee5
commit 92f7873f98
11 changed files with 733 additions and 11 deletions

83
config/config.go Normal file
View File

@@ -0,0 +1,83 @@
package config
import (
"fmt"
"gitea.suyono.dev/suyono/wingmate/debugframes"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"path"
)
const (
envPrefix = "wingmate"
configPathKey = "config_path"
configSearchPathKey = "config_search_path"
defaultPath = "/etc/wingmate/"
defaultName = "config"
serviceKey = "service"
cronKey = "cron"
)
var (
configPath string
configSearchPath []string
configRead bool
)
func init() {
viper.SetEnvPrefix(envPrefix)
_ = viper.BindEnv(configPathKey)
_ = viper.BindEnv(configSearchPathKey)
}
func BindFlags(command *cobra.Command) {
command.PersistentFlags().StringVarP(&configPath, "config", "c", defaultPath+defaultName+".yml", "configuration path")
command.PersistentFlags().StringSliceVar(&configSearchPath, "config-dir", []string{}, "configuration search path")
}
func Read(cmd *cobra.Command, args []string) error {
var (
err error
)
_, _ = cmd, args // prevent warning for unused arguments
if viper.IsSet(configPathKey) {
configPath = viper.GetString(configPathKey)
}
if viper.IsSet(configSearchPathKey) {
if err = viper.UnmarshalKey(configSearchPathKey, &configSearchPath); err != nil {
return fmt.Errorf("reading %s: %w %w", configSearchPathKey, err, debugframes.GetTraces())
}
}
if configRead {
return nil
}
viper.SetConfigType("yaml")
if len(configSearchPath) > 0 {
name := path.Base(configPath)
dir := path.Dir(configPath)
if dir != "." {
configSearchPath = append([]string{dir}, configSearchPath...)
}
viper.SetConfigName(name)
for _, p := range configSearchPath {
viper.AddConfigPath(p)
}
} else {
viper.SetConfigFile(configPath)
}
if err = viper.ReadInConfig(); err != nil {
return fmt.Errorf("reading config: %w %w", err, debugframes.GetTraces())
}
configRead = true
return nil
}

59
config/config_test.go Normal file
View File

@@ -0,0 +1,59 @@
package config
import (
"github.com/spf13/cobra"
"os"
"strings"
"testing"
)
func TestRead(t *testing.T) {
type args struct {
cmd *cobra.Command
args []string
}
tests := []struct {
name string
env map[string]string
args args
wantErr bool
}{
{
name: "env",
env: map[string]string{
strings.ToUpper(envPrefix + "_" + configPathKey): "/path/to/config",
strings.ToUpper(envPrefix + "_" + configSearchPathKey): "/path/one,/path/two",
},
args: args{
nil,
[]string{},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var err error
for k, v := range tt.env {
if err = os.Setenv(k, v); err != nil {
t.Fatal("failed", err)
}
}
defer func() {
for k := range tt.env {
if err = os.Unsetenv(k); err != nil {
t.Fatal("failed", err)
}
}
}()
if err = Read(tt.args.cmd, tt.args.args); (err != nil) != tt.wantErr {
t.Fatalf("Read() error = %v, wantErr %v", err, tt.wantErr)
}
if tt.wantErr {
t.Log("case:", tt.name, "; expected error:", err)
}
})
}
}