@@ -24,6 +24,7 @@ import (
24
24
25
25
"sigs.k8s.io/kwok/pkg/consts"
26
26
"sigs.k8s.io/kwok/pkg/log"
27
+ "sigs.k8s.io/kwok/pkg/utils/file"
27
28
"sigs.k8s.io/kwok/pkg/utils/path"
28
29
"sigs.k8s.io/kwok/pkg/utils/slices"
29
30
)
@@ -34,45 +35,59 @@ func InitFlags(ctx context.Context, flags *pflag.FlagSet) (context.Context, erro
34
35
config := flags .StringArrayP ("config" , "c" , []string {defaultConfigPath }, "config path" )
35
36
_ = flags .Parse (os .Args [1 :])
36
37
37
- existDefaultConfig := false
38
- configPath , err := path .Expand (defaultConfigPath )
39
- if err == nil {
40
- _ , err = os .Stat (configPath )
41
- if err == nil {
42
- existDefaultConfig = true
43
- }
38
+ // Expand the all config paths.
39
+ defaultConfigPath , err := path .Expand (defaultConfigPath )
40
+ if err != nil {
41
+ return nil , err
44
42
}
45
-
46
- if ! slices .Contains (* config , defaultConfigPath ) {
47
- if existDefaultConfig {
48
- * config = append ([]string {configPath }, * config ... )
49
- }
50
- } else {
51
- if ! existDefaultConfig {
52
- * config = slices .Filter (* config , func (s string ) bool {
53
- return s != defaultConfigPath
54
- })
43
+ configPaths := make ([]string , 0 , len (* config ))
44
+ for _ , c := range * config {
45
+ configPath , err := path .Expand (c )
46
+ if err != nil {
47
+ return nil , err
55
48
}
49
+ configPaths = append (configPaths , configPath )
56
50
}
57
51
52
+ configPaths = loadConfig (configPaths , defaultConfigPath , file .Exists (defaultConfigPath ))
53
+
58
54
logger := log .FromContext (ctx )
59
- objs , err := Load (ctx , * config ... )
55
+ objs , err := Load (ctx , configPaths ... )
60
56
if err != nil {
61
57
return nil , err
62
58
}
63
59
64
60
if len (objs ) == 0 {
65
61
logger .Debug ("Load config" ,
66
- "path" , * config ,
62
+ "path" , configPaths ,
67
63
"err" , "empty config" ,
68
64
)
69
65
} else {
70
66
logger .Debug ("Load config" ,
71
- "path" , * config ,
67
+ "path" , configPaths ,
72
68
"count" , len (objs ),
73
69
"content" , objs ,
74
70
)
75
71
}
76
72
77
73
return setupContext (ctx , objs ), nil
78
74
}
75
+
76
+ // loadConfig loads the config paths.
77
+ // ~/.kwok/kwok.yaml will be loaded first if it exists.
78
+ func loadConfig (configPaths []string , defaultConfigPath string , existDefaultConfig bool ) []string {
79
+ if ! slices .Contains (configPaths , defaultConfigPath ) {
80
+ if existDefaultConfig {
81
+ // If the defaultConfigPath is not specified and the default config exists, it will be loaded first.
82
+ return append ([]string {defaultConfigPath }, configPaths ... )
83
+ }
84
+ } else {
85
+ if ! existDefaultConfig {
86
+ // If the defaultConfigPath is specified and the default config does not exist, it will be removed.
87
+ return slices .Filter (configPaths , func (s string ) bool {
88
+ return s != defaultConfigPath
89
+ })
90
+ }
91
+ }
92
+ return configPaths
93
+ }
0 commit comments