github.com/lynxsecurity/viper@v1.10.0/util.go (about)

     1  // Copyright © 2014 Steve Francia <spf@spf13.com>.
     2  //
     3  // Use of this source code is governed by an MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  // Viper is a application configuration system.
     7  // It believes that applications can be configured a variety of ways
     8  // via flags, ENVIRONMENT variables, configuration files retrieved
     9  // from the file system, or a remote key/value store.
    10  
    11  package viper
    12  
    13  import (
    14  	"fmt"
    15  	"os"
    16  	"path/filepath"
    17  	"runtime"
    18  	"strings"
    19  	"unicode"
    20  
    21  	"github.com/spf13/cast"
    22  	jww "github.com/spf13/jwalterweatherman"
    23  )
    24  
    25  // ConfigParseError denotes failing to parse configuration file.
    26  type ConfigParseError struct {
    27  	err error
    28  }
    29  
    30  // Error returns the formatted configuration error.
    31  func (pe ConfigParseError) Error() string {
    32  	return fmt.Sprintf("While parsing config: %s", pe.err.Error())
    33  }
    34  
    35  // toCaseInsensitiveValue checks if the value is a  map;
    36  // if so, create a copy and lower-case the keys recursively.
    37  func toCaseInsensitiveValue(value interface{}) interface{} {
    38  	switch v := value.(type) {
    39  	case map[interface{}]interface{}:
    40  		value = copyAndInsensitiviseMap(cast.ToStringMap(v))
    41  	case map[string]interface{}:
    42  		value = copyAndInsensitiviseMap(v)
    43  	}
    44  
    45  	return value
    46  }
    47  
    48  // copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
    49  // any map it makes case insensitive.
    50  func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
    51  	nm := make(map[string]interface{})
    52  
    53  	for key, val := range m {
    54  		lkey := strings.ToLower(key)
    55  		switch v := val.(type) {
    56  		case map[interface{}]interface{}:
    57  			nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
    58  		case map[string]interface{}:
    59  			nm[lkey] = copyAndInsensitiviseMap(v)
    60  		default:
    61  			nm[lkey] = v
    62  		}
    63  	}
    64  
    65  	return nm
    66  }
    67  
    68  func insensitiviseMap(m map[string]interface{}) {
    69  	for key, val := range m {
    70  		switch val.(type) {
    71  		case map[interface{}]interface{}:
    72  			// nested map: cast and recursively insensitivise
    73  			val = cast.ToStringMap(val)
    74  			insensitiviseMap(val.(map[string]interface{}))
    75  		case map[string]interface{}:
    76  			// nested map: recursively insensitivise
    77  			insensitiviseMap(val.(map[string]interface{}))
    78  		}
    79  
    80  		lower := strings.ToLower(key)
    81  		if key != lower {
    82  			// remove old key (not lower-cased)
    83  			delete(m, key)
    84  		}
    85  		// update map
    86  		m[lower] = val
    87  	}
    88  }
    89  
    90  func absPathify(inPath string) string {
    91  	jww.INFO.Println("Trying to resolve absolute path to", inPath)
    92  
    93  	if inPath == "$HOME" || strings.HasPrefix(inPath, "$HOME"+string(os.PathSeparator)) {
    94  		inPath = userHomeDir() + inPath[5:]
    95  	}
    96  
    97  	inPath = os.ExpandEnv(inPath)
    98  
    99  	if filepath.IsAbs(inPath) {
   100  		return filepath.Clean(inPath)
   101  	}
   102  
   103  	p, err := filepath.Abs(inPath)
   104  	if err == nil {
   105  		return filepath.Clean(p)
   106  	}
   107  
   108  	jww.ERROR.Println("Couldn't discover absolute path")
   109  	jww.ERROR.Println(err)
   110  	return ""
   111  }
   112  
   113  func stringInSlice(a string, list []string) bool {
   114  	for _, b := range list {
   115  		if b == a {
   116  			return true
   117  		}
   118  	}
   119  	return false
   120  }
   121  
   122  func userHomeDir() string {
   123  	if runtime.GOOS == "windows" {
   124  		home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
   125  		if home == "" {
   126  			home = os.Getenv("USERPROFILE")
   127  		}
   128  		return home
   129  	}
   130  	return os.Getenv("HOME")
   131  }
   132  
   133  func safeMul(a, b uint) uint {
   134  	c := a * b
   135  	if a > 1 && b > 1 && c/b != a {
   136  		return 0
   137  	}
   138  	return c
   139  }
   140  
   141  // parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes
   142  func parseSizeInBytes(sizeStr string) uint {
   143  	sizeStr = strings.TrimSpace(sizeStr)
   144  	lastChar := len(sizeStr) - 1
   145  	multiplier := uint(1)
   146  
   147  	if lastChar > 0 {
   148  		if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' {
   149  			if lastChar > 1 {
   150  				switch unicode.ToLower(rune(sizeStr[lastChar-1])) {
   151  				case 'k':
   152  					multiplier = 1 << 10
   153  					sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
   154  				case 'm':
   155  					multiplier = 1 << 20
   156  					sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
   157  				case 'g':
   158  					multiplier = 1 << 30
   159  					sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
   160  				default:
   161  					multiplier = 1
   162  					sizeStr = strings.TrimSpace(sizeStr[:lastChar])
   163  				}
   164  			}
   165  		}
   166  	}
   167  
   168  	size := cast.ToInt(sizeStr)
   169  	if size < 0 {
   170  		size = 0
   171  	}
   172  
   173  	return safeMul(uint(size), multiplier)
   174  }
   175  
   176  // deepSearch scans deep maps, following the key indexes listed in the
   177  // sequence "path".
   178  // The last value is expected to be another map, and is returned.
   179  //
   180  // In case intermediate keys do not exist, or map to a non-map value,
   181  // a new map is created and inserted, and the search continues from there:
   182  // the initial map "m" may be modified!
   183  func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
   184  	for _, k := range path {
   185  		m2, ok := m[k]
   186  		if !ok {
   187  			// intermediate key does not exist
   188  			// => create it and continue from there
   189  			m3 := make(map[string]interface{})
   190  			m[k] = m3
   191  			m = m3
   192  			continue
   193  		}
   194  		m3, ok := m2.(map[string]interface{})
   195  		if !ok {
   196  			// intermediate key is a value
   197  			// => replace with a new map
   198  			m3 = make(map[string]interface{})
   199  			m[k] = m3
   200  		}
   201  		// continue search from here
   202  		m = m3
   203  	}
   204  	return m
   205  }