()
| 133 | } |
| 134 | |
| 135 | func loadConfig() (*app.Config, bool, error) { |
| 136 | const ( |
| 137 | configFileOption = "config.file" |
| 138 | configExpandEnvOption = "config.expand-env" |
| 139 | configVerifyOption = "config.verify" |
| 140 | ) |
| 141 | |
| 142 | var ( |
| 143 | configFile string |
| 144 | configExpandEnv bool |
| 145 | configVerify bool |
| 146 | ) |
| 147 | |
| 148 | args := os.Args[1:] |
| 149 | config := &app.Config{} |
| 150 | |
| 151 | // first get the config file |
| 152 | fs := flag.NewFlagSet("", flag.ContinueOnError) |
| 153 | fs.SetOutput(io.Discard) |
| 154 | |
| 155 | fs.StringVar(&configFile, configFileOption, "", "") |
| 156 | fs.BoolVar(&configExpandEnv, configExpandEnvOption, false, "") |
| 157 | fs.BoolVar(&configVerify, configVerifyOption, false, "") |
| 158 | |
| 159 | // Try to find -config.file & -config.expand-env flags. As Parsing stops on the first error, eg. unknown flag, |
| 160 | // we simply try remaining parameters until we find config flag, or there are no params left. |
| 161 | // (ContinueOnError just means that flag.Parse doesn't call panic or os.Exit, but it returns error, which we ignore) |
| 162 | for len(args) > 0 { |
| 163 | _ = fs.Parse(args) |
| 164 | args = args[1:] |
| 165 | } |
| 166 | |
| 167 | // load config defaults and register flags |
| 168 | config.RegisterFlagsAndApplyDefaults("", flag.CommandLine) |
| 169 | |
| 170 | // overlay with config file if provided |
| 171 | if configFile != "" { |
| 172 | buff, err := os.ReadFile(configFile) |
| 173 | if err != nil { |
| 174 | return nil, false, fmt.Errorf("failed to read configFile %s: %w", configFile, err) |
| 175 | } |
| 176 | |
| 177 | if configExpandEnv { |
| 178 | s, err := envsubst.EvalEnv(string(buff)) |
| 179 | if err != nil { |
| 180 | return nil, false, fmt.Errorf("failed to expand env vars from configFile %s: %w", configFile, err) |
| 181 | } |
| 182 | buff = []byte(s) |
| 183 | } |
| 184 | |
| 185 | err = yaml.UnmarshalStrict(buff, config) |
| 186 | if err != nil { |
| 187 | return nil, false, fmt.Errorf("failed to parse configFile %s: %w", configFile, err) |
| 188 | } |
| 189 | |
| 190 | } |
| 191 | |
| 192 | // Pass --config.expand-env flag to overrides module |
no test coverage detected