github.com/joshdk/godel@v0.0.0-20170529232908-862138a45aee/properties/reader.go (about) 1 // Copyright 2016 Palantir Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package properties 16 17 import ( 18 "fmt" 19 "io/ioutil" 20 "strings" 21 ) 22 23 const URL = "distributionURL" 24 const Checksum = "distributionSHA256" 25 26 // Read reads the file at the provided path and returns a map of the properties that it contains. The file should 27 // contain one property per line and the line should be of the form "key=value". Any line that starts with the character 28 // '#' is ignored. 29 func Read(path string) (map[string]string, error) { 30 bytes, err := ioutil.ReadFile(path) 31 if err != nil { 32 return nil, fmt.Errorf("Failed to read file %v: %v", path, err) 33 } 34 35 properties := make(map[string]string) 36 37 lines := strings.Split(string(bytes), "\n") 38 for _, currLine := range lines { 39 currLine = strings.TrimSpace(currLine) 40 41 if strings.HasPrefix(currLine, "#") || len(currLine) == 0 { 42 continue 43 } 44 45 equalsIndex := strings.IndexAny(currLine, "=") 46 if equalsIndex == -1 { 47 return nil, fmt.Errorf(`Failed to find character "=" in line "%v" in file with lines "%v"`, currLine, lines) 48 } 49 50 properties[currLine[:equalsIndex]] = currLine[equalsIndex+1:] 51 } 52 return properties, nil 53 } 54 55 // Get returns the specified property from the provided map or returns an error if the requested key does not exist 56 // in the provided map. 57 func Get(properties map[string]string, key string) (string, error) { 58 if value, ok := properties[key]; ok { 59 return value, nil 60 } 61 return "", fmt.Errorf("property %v did not exist in map %v", key, properties) 62 }