github.com/elliott5/community@v0.14.1-0.20160709191136-823126fb026a/wordsmith/environment/environment.go (about)

     1  // Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
     2  //
     3  // This software (Documize Community Edition) is licensed under 
     4  // GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
     5  //
     6  // You can operate outside the AGPL restrictions by purchasing
     7  // Documize Enterprise Edition and obtaining a commercial license
     8  // by contacting <sales@documize.com>. 
     9  //
    10  // https://documize.com
    11  
    12  // Package environment allow environment variables to be obtained from either the environment or the command line.
    13  // Environment variables are always uppercase, with the Prefix; flags are always lowercase without.
    14  package environment
    15  
    16  import (
    17  	"flag"
    18  	"fmt"
    19  	"os"
    20  	"sort"
    21  	"strings"
    22  )
    23  
    24  // CallbackT is the type signature of the callback function of GetString().
    25  type CallbackT func(*string, string) bool
    26  
    27  type varT struct {
    28  	target              *string
    29  	name, setter, value string
    30  	required            bool
    31  	callback            CallbackT
    32  }
    33  
    34  type varsT struct {
    35  	vv []varT
    36  }
    37  
    38  var vars varsT
    39  
    40  // Len is part of sort.Interface.
    41  func (v *varsT) Len() int {
    42  	return len(v.vv)
    43  }
    44  
    45  // Swap is part of sort.Interface.
    46  func (v *varsT) Swap(i, j int) {
    47  	v.vv[i], v.vv[j] = v.vv[j], v.vv[i]
    48  }
    49  
    50  // Less is part of sort.Interface.
    51  func (v *varsT) Less(i, j int) bool {
    52  	return v.vv[i].name < v.vv[j].name
    53  }
    54  
    55  // Prefix provides the prefix for all Environment variables
    56  const Prefix = "DOCUMIZE"
    57  
    58  const goInit = "(default)"
    59  
    60  // GetString sets-up the flag for later use, it must be called before ParseOK(), usually in an init().
    61  func GetString(target *string, name string, required bool, usage string, callback CallbackT) {
    62  	name = strings.ToLower(strings.TrimSpace(name))
    63  	setter := Prefix + strings.ToUpper(name)
    64  	value := os.Getenv(setter)
    65  	if value == "" {
    66  		value = *target // use the Go initialized value
    67  		setter = goInit
    68  	}
    69  	flag.StringVar(target, name, value, usage)
    70  	vars.vv = append(vars.vv, varT{target: target, name: name, required: required, callback: callback, value: value, setter: setter})
    71  }
    72  
    73  var showSettings = flag.Bool("showsettings", false, "if true, show settings in the log (WARNING: these settings may include passwords)")
    74  
    75  // Parse calls flag.Parse() then checks that the required environment variables are all set.
    76  // It should be the first thing called by any main() that uses this library.
    77  // If all the required variables are not present, it prints an error and calls os.Exit(2) like flag.Parse().
    78  func Parse(doFirst string) {
    79  	flag.Parse()
    80  	sort.Sort(&vars)
    81  	for pass := 1; pass <= 2; pass++ {
    82  		for vi, v := range vars.vv {
    83  			if (pass == 1 && v.name == doFirst) || (pass == 2 && v.name != doFirst) {
    84  				typ := "Optional"
    85  				if v.value != *(v.target) || (v.value != "" && *(v.target) == "") {
    86  					vars.vv[vi].setter = "-" + v.name // v is a local copy, not the underlying data
    87  				}
    88  				if v.callback != nil {
    89  					if v.callback(v.target, v.name) {
    90  						vars.vv[vi].setter = "setting:" + v.name // v is a local copy, not the underlying data
    91  					}
    92  				}
    93  				if v.required {
    94  					if *(v.target) == "" {
    95  						fmt.Fprintln(os.Stderr)
    96  						fmt.Fprintln(os.Stderr, "In order to run", os.Args[0], "the following must be provided:")
    97  						for _, vv := range vars.vv {
    98  							if vv.required {
    99  								fmt.Fprintf(os.Stderr, "* setting from environment variable '%s' or flag '-%s' or an application setting '%s', current value: '%s' set by '%s'\n",
   100  									Prefix+strings.ToUpper(vv.name), vv.name, vv.name, *(vv.target), vv.setter)
   101  							}
   102  						}
   103  						fmt.Fprintln(os.Stderr)
   104  						flag.Usage()
   105  						os.Exit(2)
   106  						return
   107  					}
   108  					typ = "Required"
   109  				}
   110  				if *showSettings {
   111  					if *(v.target) != "" && vars.vv[vi].setter != goInit {
   112  						fmt.Fprintf(os.Stdout, "%s setting from '%s' is: '%s'\n",
   113  							typ, vars.vv[vi].setter, *(v.target))
   114  					}
   115  				}
   116  			}
   117  		}
   118  	}
   119  }