github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/opts/env.go (about)

     1  package opts
     2  
     3  import (
     4  	"os"
     5  	"strings"
     6  
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  // ValidateEnv validates an environment variable and returns it.
    11  // If no value is specified, it obtains its value from the current environment
    12  //
    13  // As on ParseEnvFile and related to #16585, environment variable names
    14  // are not validated, and it's up to the application inside the container
    15  // to validate them or not.
    16  //
    17  // The only validation here is to check if name is empty, per #25099
    18  func ValidateEnv(val string) (string, error) {
    19  	k, _, hasValue := strings.Cut(val, "=")
    20  	if k == "" {
    21  		return "", errors.New("invalid environment variable: " + val)
    22  	}
    23  	if hasValue {
    24  		// val contains a "=" (but value may be an empty string)
    25  		return val, nil
    26  	}
    27  	if envVal, ok := os.LookupEnv(k); ok {
    28  		return k + "=" + envVal, nil
    29  	}
    30  	return val, nil
    31  }