sigs.k8s.io/prow@v0.0.0-20240503223140-c5e374dc7eb1/pkg/pod-utils/options/load.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package options 18 19 import ( 20 "flag" 21 "fmt" 22 "os" 23 ) 24 25 // OptionLoader allows loading options from either the environment or flags. 26 type OptionLoader interface { 27 ConfigVar() string 28 LoadConfig(config string) error 29 AddFlags(flags *flag.FlagSet) 30 Complete(args []string) 31 } 32 33 // Load loads the set of options, preferring to use 34 // JSON config from an env var, but falling back to 35 // command line flags if not possible. 36 func Load(loader OptionLoader) error { 37 if jsonConfig, provided := os.LookupEnv(loader.ConfigVar()); provided { 38 if err := loader.LoadConfig(jsonConfig); err != nil { 39 return fmt.Errorf("could not load config from JSON var %s: %w", loader.ConfigVar(), err) 40 } 41 return nil 42 } 43 44 fs := flag.NewFlagSet(os.Args[0], flag.ExitOnError) 45 loader.AddFlags(fs) 46 fs.Parse(os.Args[1:]) 47 loader.Complete(fs.Args()) 48 49 return nil 50 }