github.com/clysto/awgo@v0.15.0/env.go (about)

     1  //
     2  // Copyright (c) 2018 Dean Jackson <deanishe@deanishe.net>
     3  //
     4  // MIT Licence. See http://opensource.org/licenses/MIT
     5  //
     6  // Created on 2018-06-30
     7  //
     8  
     9  package aw
    10  
    11  import (
    12  	"fmt"
    13  	"os"
    14  	"strings"
    15  )
    16  
    17  // Env is the datasource for configuration lookups.
    18  //
    19  // Pass a custom implementation to NewFromEnv() to provide a custom
    20  // source for the required workflow configuration settings.
    21  //
    22  // As an absolute minimum, the following variables must be set:
    23  //
    24  //     alfred_workflow_bundleid
    25  //     alfred_workflow_cache
    26  //     alfred_workflow_data
    27  //
    28  // See EnvVar* consts for all variables set by Alfred.
    29  type Env interface {
    30  	// Lookup retrieves the value of the variable named by key.
    31  	//
    32  	// It follows the same semantics as os.LookupEnv(). If a variable
    33  	// is unset, the boolean will be false. If a variable is set, the
    34  	// boolean will be true, but the variable may still be an empty
    35  	// string.
    36  	Lookup(key string) (string, bool)
    37  }
    38  
    39  // MapEnv is a testing helper that makes it simple to convert a map[string]string
    40  // to an Env.
    41  type MapEnv map[string]string
    42  
    43  // Lookup implements Env. It returns values from the map.
    44  func (env MapEnv) Lookup(key string) (string, bool) {
    45  	s, ok := env[key]
    46  	return s, ok
    47  }
    48  
    49  // sysEnv implements Env based on the real environment.
    50  type sysEnv struct{}
    51  
    52  // Lookup wraps os.LookupEnv().
    53  func (e sysEnv) Lookup(key string) (string, bool) { return os.LookupEnv(key) }
    54  
    55  // Check that minimum required values are set.
    56  func validateEnv(env Env) error {
    57  
    58  	var (
    59  		issues   []string
    60  		required = []string{
    61  			EnvVarBundleID,
    62  			EnvVarCacheDir,
    63  			EnvVarDataDir,
    64  		}
    65  	)
    66  
    67  	for _, k := range required {
    68  		v, ok := env.Lookup(k)
    69  		if !ok || v == "" {
    70  			issues = append(issues, k+" is not set")
    71  		}
    72  	}
    73  
    74  	if issues != nil {
    75  		return fmt.Errorf("Invalid Workflow environment: %s", strings.Join(issues, ", "))
    76  	}
    77  
    78  	return nil
    79  }