github.com/schwarzm/garden-linux@v0.0.0-20150507151835-33bca2147c47/process/env.go (about)

     1  package process
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"sort"
     8  	"strings"
     9  )
    10  
    11  type Env map[string]string
    12  
    13  func NewEnv(array []string) (Env, error) {
    14  	env := make(Env, len(array))
    15  
    16  	for _, str := range array {
    17  		if str == "" {
    18  			return nil, errors.New("process: malformed environment: empty string")
    19  		}
    20  
    21  		tokens := strings.SplitN(str, "=", 2)
    22  
    23  		if len(tokens) != 2 {
    24  			return nil, fmt.Errorf("process: malformed environment: invalid format (not key=value): %q", str)
    25  		}
    26  
    27  		key, value := tokens[0], tokens[1]
    28  
    29  		if key == "" {
    30  			return nil, fmt.Errorf("process: malformed environment: empty key: %q", str)
    31  		}
    32  
    33  		env[key] = value
    34  	}
    35  
    36  	return env, nil
    37  }
    38  
    39  func (env Env) Merge(other Env) Env {
    40  	merged := make(Env, len(env)+len(other))
    41  
    42  	for key, value := range env {
    43  		merged[key] = value
    44  	}
    45  
    46  	for key, value := range other {
    47  		merged[key] = value
    48  	}
    49  
    50  	return merged
    51  }
    52  
    53  func (env Env) Array() []string {
    54  	array := make([]string, len(env))
    55  
    56  	i := 0
    57  	for key, value := range env {
    58  		array[i] = fmt.Sprintf("%s=%s", key, value)
    59  		i++
    60  	}
    61  
    62  	sort.Strings(array)
    63  
    64  	return array
    65  }
    66  
    67  func (env Env) String() string {
    68  	return fmt.Sprintf("%#v", env)
    69  }
    70  
    71  func EnvFromFile(filePath string) (Env, error) {
    72  	f, err := ioutil.ReadFile(filePath)
    73  	if err != nil {
    74  		return nil, fmt.Errorf("process: EnvFromFile: %s", err)
    75  	}
    76  	lines := strings.Split(strings.TrimSpace(string(f)), "\n")
    77  	nonEmptyLines := []string{}
    78  	for _, line := range lines {
    79  		if line != "" {
    80  			nonEmptyLines = append(nonEmptyLines, line)
    81  		}
    82  	}
    83  	return NewEnv(nonEmptyLines)
    84  }