-
Notifications
You must be signed in to change notification settings - Fork 9
/
config.go
109 lines (91 loc) · 2.3 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package cmd
import (
"fmt"
"os"
"strings"
"github.com/jlewi/foyle/app/pkg/config"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)
// NewConfigCmd adds commands to deal with configuration
func NewConfigCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "config",
}
cmd.AddCommand(NewGetConfigCmd())
cmd.AddCommand(NewSetConfigCmd())
return cmd
}
// NewSetConfigCmd sets a key value pair in the configuration
func NewSetConfigCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "set <name>=<value>",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
err := func() error {
if err := config.InitViper(cmd); err != nil {
return err
}
pieces := strings.Split(args[0], "=")
cfgName := pieces[0]
var fConfig *config.Config
switch cfgName {
case "azureOpenAI.deployments":
if len(pieces) != 3 {
return errors.New("Invalid argument; argument is not in the form azureOpenAI.deployments=<model>=<deployment>")
}
d := config.AzureDeployment{
Model: pieces[1],
Deployment: pieces[2],
}
fConfig = config.GetConfig()
config.SetAzureDeployment(fConfig, d)
default:
if len(pieces) < 2 {
return errors.New("Invalid usage; set expects an argument in the form <NAME>=<VALUE>")
}
cfgValue := pieces[1]
viper.Set(cfgName, cfgValue)
fConfig = config.GetConfig()
}
file := viper.ConfigFileUsed()
if file == "" {
file = config.DefaultConfigFile()
}
// Persist the configuration
return fConfig.Write(file)
}()
if err != nil {
fmt.Printf("Failed to set configuration;\n %+v\n", err)
os.Exit(1)
}
},
}
return cmd
}
// NewGetConfigCmd prints out the configuration
func NewGetConfigCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "get",
Short: "Dump Foyle configuration as YAML",
Run: func(cmd *cobra.Command, args []string) {
err := func() error {
if err := config.InitViper(cmd); err != nil {
return err
}
fConfig := config.GetConfig()
if err := yaml.NewEncoder(os.Stdout).Encode(fConfig); err != nil {
return err
}
return nil
}()
if err != nil {
fmt.Printf("Failed to get configuration;\n %+v\n", err)
os.Exit(1)
}
},
}
return cmd
}