github.com/wynshop-open-source/gomplate@v3.5.0+incompatible/env/env.go (about)

     1  // Package env contains functions that retrieve data from the environment
     2  package env
     3  
     4  import (
     5  	"io/ioutil"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/spf13/afero"
    10  )
    11  
    12  // Getenv - retrieves the value of the environment variable named by the key.
    13  // If the variable is unset, but the same variable ending in `_FILE` is set, the
    14  // referenced file will be read into the value.
    15  // Otherwise the provided default (or an emptry string) is returned.
    16  func Getenv(key string, def ...string) string {
    17  	return getenvVFS(afero.NewOsFs(), key, def...)
    18  }
    19  
    20  // ExpandEnv - like os.ExpandEnv, except supports `_FILE` vars as well
    21  func ExpandEnv(s string) string {
    22  	return expandEnvVFS(afero.NewOsFs(), s)
    23  }
    24  
    25  // expandEnvVFS -
    26  func expandEnvVFS(fs afero.Fs, s string) string {
    27  	return os.Expand(s, func(s string) string {
    28  		return getenvVFS(fs, s)
    29  	})
    30  }
    31  
    32  // getenvVFS - a convenience function intended for internal use only!
    33  func getenvVFS(fs afero.Fs, key string, def ...string) string {
    34  	val := getenvFile(fs, key)
    35  	if val == "" && len(def) > 0 {
    36  		return def[0]
    37  	}
    38  
    39  	return val
    40  }
    41  
    42  func getenvFile(fs afero.Fs, key string) string {
    43  	val := os.Getenv(key)
    44  	if val != "" {
    45  		return val
    46  	}
    47  
    48  	p := os.Getenv(key + "_FILE")
    49  	if p != "" {
    50  		val, err := readFile(fs, p)
    51  		if err != nil {
    52  			return ""
    53  		}
    54  		return strings.TrimSpace(val)
    55  	}
    56  
    57  	return ""
    58  }
    59  
    60  func readFile(fs afero.Fs, p string) (string, error) {
    61  	f, err := fs.OpenFile(p, os.O_RDONLY, 0)
    62  	if err != nil {
    63  		return "", err
    64  	}
    65  	b, err := ioutil.ReadAll(f)
    66  	if err != nil {
    67  		return "", err
    68  	}
    69  	return string(b), nil
    70  }