@@ -3,6 +3,10 @@ package cli
33import (
44 "fmt"
55 "os"
6+ "path/filepath"
7+ "strings"
8+
9+ "dict-be/internal/config"
610
711 "github.com/spf13/cobra"
812 "github.com/spf13/viper"
@@ -14,6 +18,10 @@ type Options struct {
1418
1519func NewRootCmd () * cobra.Command {
1620 opts := & Options {}
21+ defaultConfigPath := ""
22+ if homeDir , err := os .UserHomeDir (); err == nil {
23+ defaultConfigPath = filepath .Join (homeDir , ".dict-be.yml" )
24+ }
1725 root := & cobra.Command {
1826 Use : "dict-be" ,
1927 Short : "dict-be - CLI starter" ,
@@ -26,8 +34,8 @@ func NewRootCmd() *cobra.Command {
2634 root .PersistentFlags ().StringVar (
2735 & opts .Config ,
2836 "config" ,
29- "" ,
30- "config file (default: ./ dict-be.yaml )" ,
37+ defaultConfigPath ,
38+ "config file (default: ~/. dict-be.yml )" ,
3139 )
3240 _ = viper .BindPFlag ("config" , root .PersistentFlags ().Lookup ("config" ))
3341
@@ -36,22 +44,46 @@ func NewRootCmd() *cobra.Command {
3644}
3745
3846func initConfig (configFile string ) {
47+ configFile = strings .TrimSpace (configFile )
3948 if configFile != "" {
40- viper .SetConfigFile (configFile )
49+ viper .SetConfigFile (expandHome ( configFile ) )
4150 } else {
42- viper .SetConfigName ("dict-be" )
43- viper .SetConfigType ("yaml" )
44- viper .AddConfigPath ("." )
45- viper .AddConfigPath ("$HOME/.config/dict-be" )
51+ if homeDir , err := os .UserHomeDir (); err == nil {
52+ viper .SetConfigFile (filepath .Join (homeDir , ".dict-be.yml" ))
53+ }
4654 }
4755
4856 viper .SetEnvPrefix ("DICT_BE" )
4957 viper .AutomaticEnv ()
58+ viper .SetDefault ("llm.url" , "" )
59+ viper .SetDefault ("llm.model" , "" )
60+ viper .SetDefault ("llm.token" , "" )
61+ viper .SetDefault ("llm.type" , "" )
5062
5163 if err := viper .ReadInConfig (); err != nil {
5264 if _ , ok := err .(viper.ConfigFileNotFoundError ); ok {
5365 return
5466 }
5567 fmt .Fprintln (os .Stderr , err .Error ())
68+ return
69+ }
70+
71+ if _ , err := config .Load (); err != nil {
72+ fmt .Fprintln (os .Stderr , err .Error ())
73+ }
74+ }
75+
76+ func expandHome (path string ) string {
77+ if path == "~" {
78+ if homeDir , err := os .UserHomeDir (); err == nil {
79+ return homeDir
80+ }
81+ return path
82+ }
83+ if strings .HasPrefix (path , "~/" ) {
84+ if homeDir , err := os .UserHomeDir (); err == nil {
85+ return filepath .Join (homeDir , strings .TrimPrefix (path , "~/" ))
86+ }
5687 }
88+ return path
5789}
0 commit comments