github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/runconfig/opts/parse.go (about)

     1  package opts
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  	"strings"
     7  
     8  	"github.com/docker/docker/api/types/container"
     9  )
    10  
    11  // ReadKVStrings reads a file of line terminated key=value pairs, and overrides any keys
    12  // present in the file with additional pairs specified in the override parameter
    13  func ReadKVStrings(files []string, override []string) ([]string, error) {
    14  	envVariables := []string{}
    15  	for _, ef := range files {
    16  		parsedVars, err := ParseEnvFile(ef)
    17  		if err != nil {
    18  			return nil, err
    19  		}
    20  		envVariables = append(envVariables, parsedVars...)
    21  	}
    22  	// parse the '-e' and '--env' after, to allow override
    23  	envVariables = append(envVariables, override...)
    24  
    25  	return envVariables, nil
    26  }
    27  
    28  // ConvertKVStringsToMap converts ["key=value"] to {"key":"value"}
    29  func ConvertKVStringsToMap(values []string) map[string]string {
    30  	result := make(map[string]string, len(values))
    31  	for _, value := range values {
    32  		kv := strings.SplitN(value, "=", 2)
    33  		if len(kv) == 1 {
    34  			result[kv[0]] = ""
    35  		} else {
    36  			result[kv[0]] = kv[1]
    37  		}
    38  	}
    39  
    40  	return result
    41  }
    42  
    43  // ConvertKVStringsToMapWithNil converts ["key=value"] to {"key":"value"}
    44  // but set unset keys to nil - meaning the ones with no "=" in them.
    45  // We use this in cases where we need to distinguish between
    46  //   FOO=  and FOO
    47  // where the latter case just means FOO was mentioned but not given a value
    48  func ConvertKVStringsToMapWithNil(values []string) map[string]*string {
    49  	result := make(map[string]*string, len(values))
    50  	for _, value := range values {
    51  		kv := strings.SplitN(value, "=", 2)
    52  		if len(kv) == 1 {
    53  			result[kv[0]] = nil
    54  		} else {
    55  			result[kv[0]] = &kv[1]
    56  		}
    57  	}
    58  
    59  	return result
    60  }
    61  
    62  // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect
    63  func ParseRestartPolicy(policy string) (container.RestartPolicy, error) {
    64  	p := container.RestartPolicy{}
    65  
    66  	if policy == "" {
    67  		return p, nil
    68  	}
    69  
    70  	parts := strings.Split(policy, ":")
    71  
    72  	if len(parts) > 2 {
    73  		return p, fmt.Errorf("invalid restart policy format")
    74  	}
    75  	if len(parts) == 2 {
    76  		count, err := strconv.Atoi(parts[1])
    77  		if err != nil {
    78  			return p, fmt.Errorf("maximum retry count must be an integer")
    79  		}
    80  
    81  		p.MaximumRetryCount = count
    82  	}
    83  
    84  	p.Name = parts[0]
    85  
    86  	return p, nil
    87  }