go.uber.org/yarpc@v1.72.1/internal/service-test/config.go (about) 1 // Copyright (c) 2022 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package main 22 23 import ( 24 "errors" 25 "fmt" 26 "io/ioutil" 27 "os" 28 29 "gopkg.in/yaml.v2" 30 ) 31 32 var ( 33 errConfigNil = errors.New("config nil") 34 errConfigRunNotSet = errors.New("config run not set") 35 ) 36 37 type config struct { 38 RequiredEnvVars []string `json:"required_env_vars,omitempty" yaml:"required_env_vars,omitempty"` 39 Run []*cmdConfig `json:"run,omitempty" yaml:"run,omitempty"` 40 } 41 42 type cmdConfig struct { 43 Command string `json:"command,omitempty" yaml:"command,omitempty"` 44 SleepMs int `json:"sleep_ms,omitempty" yaml:"sleep_ms,omitempty"` 45 Input string `json:"input,omitempty" yaml:"input,omitempty"` 46 Output string `json:"output,omitempty" yaml:"output,omitempty"` 47 } 48 49 func newConfig(configFilePath string) (*config, error) { 50 data, err := ioutil.ReadFile(configFilePath) 51 if err != nil { 52 return nil, err 53 } 54 config := &config{} 55 if err := yaml.Unmarshal(data, config); err != nil { 56 return nil, err 57 } 58 if err := config.validate(); err != nil { 59 return nil, err 60 } 61 return config, nil 62 } 63 64 func (c *config) Cmds(dir string, debug bool) ([]*cmd, error) { 65 cmds := make([]*cmd, 0, len(c.Run)) 66 for _, cmdConfig := range c.Run { 67 cmd, err := newCmd(cmdConfig, dir, debug) 68 if err != nil { 69 return nil, err 70 } 71 cmds = append(cmds, cmd) 72 } 73 return cmds, nil 74 } 75 76 func (c *config) validate() error { 77 if c == nil { 78 return errConfigNil 79 } 80 if len(c.Run) == 0 { 81 return errConfigRunNotSet 82 } 83 for _, requiredEnvVar := range c.RequiredEnvVars { 84 if os.Getenv(requiredEnvVar) == "" { 85 return fmt.Errorf("environment variable %s must be set", requiredEnvVar) 86 } 87 } 88 return nil 89 }