github.com/mutagen-io/mutagen@v0.18.0-rc1/pkg/environment/map.go (about)

     1  package environment
     2  
     3  import (
     4  	"strings"
     5  )
     6  
     7  // ToMap converts an environment variable specification from a slice of
     8  // "KEY=value" strings to a map with equivalent contents. Any entries not
     9  // adhering to the specified format are ignored. Entries are processed in order,
    10  // meaning that the last entry seen for a key will be what populates the map.
    11  func ToMap(environment []string) map[string]string {
    12  	// Allocate result storage.
    13  	result := make(map[string]string, len(environment))
    14  
    15  	// Convert variables.
    16  	for _, specification := range environment {
    17  		keyValue := strings.SplitN(specification, "=", 2)
    18  		if len(keyValue) != 2 {
    19  			continue
    20  		}
    21  		result[keyValue[0]] = keyValue[1]
    22  	}
    23  
    24  	// Done.
    25  	return result
    26  }
    27  
    28  // FromMap converts a map of environment variables into a slice of "KEY=value"
    29  // strings. If the provided environment is nil, then the resulting slice will be
    30  // nil. If the provided environment is non-nil but empty, then the resulting
    31  // slice will be empty. These two properties are critical to usage with the
    32  // os/exec package.
    33  func FromMap(environment map[string]string) []string {
    34  	// If the environment is nil, then return a nil slice.
    35  	if environment == nil {
    36  		return nil
    37  	}
    38  
    39  	// Allocate result storage.
    40  	result := make([]string, 0, len(environment))
    41  
    42  	// Convert entries.
    43  	for key, value := range environment {
    44  		result = append(result, key+"="+value)
    45  	}
    46  
    47  	// Done.
    48  	return result
    49  }