github.com/delicb/asdf-exec@v0.1.3-0.20220111003559-af5f44250ab7/config.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path" 8 "strings" 9 ) 10 11 // Config contains asdf configuration 12 type Config struct { 13 // Whether to use legacy version files such as .python-version 14 LegacyVersionFile bool 15 } 16 17 // ParseBool parses a bool from a string 18 func ParseBool(boolStr string) (bool, error) { 19 boolStr = strings.ToLower(boolStr) 20 if boolStr == "yes" || boolStr == "1" || boolStr == "true" { 21 return true, nil 22 } else if boolStr == "no" || boolStr == "0" || boolStr == "false" { 23 return false, nil 24 } else { 25 return false, fmt.Errorf("unexepected boolean value: %s", boolStr) 26 } 27 } 28 29 // ConfigFromString returns a config from a string 30 func ConfigFromString(content string) (config Config, err error) { 31 for _, line := range ReadLines(content) { 32 tokens := strings.Split(line, "=") 33 if len(tokens) != 2 { 34 return config, fmt.Errorf("invalid line in configuration file: ") 35 } 36 key := strings.TrimSpace(tokens[0]) 37 rawValue := strings.TrimSpace(tokens[1]) 38 value, err := ParseBool(rawValue) 39 if err != nil { 40 return config, err 41 } 42 if key == "legacy_version_file" { 43 config.LegacyVersionFile = value 44 } 45 } 46 return 47 } 48 49 // ConfigFromFile returns a config from the given configuration file 50 func ConfigFromFile(filepath string) (Config, error) { 51 defaultConfig := Config{LegacyVersionFile: false} 52 if _, err := os.Stat(filepath); err != nil { 53 return defaultConfig, nil 54 } 55 content, err := ioutil.ReadFile(filepath) 56 if err != nil { 57 return defaultConfig, err 58 } 59 return ConfigFromString(string(content)) 60 } 61 62 // ConfigFromDefaultFile returns a config from the default configuration file 63 func ConfigFromDefaultFile() (Config, error) { 64 filepath := path.Join(os.Getenv("HOME"), ".asdfrc") 65 return ConfigFromFile(filepath) 66 }