github.com/ChicK00o/awgo@v0.29.4/config_bind.go (about)

     1  // Copyright (c) 2018 Dean Jackson <deanishe@deanishe.net>
     2  // MIT Licence - http://opensource.org/licenses/MIT
     3  
     4  package aw
     5  
     6  import (
     7  	"sort"
     8  
     9  	"go.deanishe.net/env"
    10  )
    11  
    12  // To populates (tagged) struct v with values from the environment.
    13  func (cfg *Config) To(v interface{}) error {
    14  	return env.Bind(v, cfg)
    15  }
    16  
    17  // From saves the fields of (tagged) struct v to the workflow's settings in Alfred.
    18  // All supported and unignored fields are saved by default. The behaviour can be
    19  // customised by passing in options from deanishe/go-env, such as env.IgnoreZeroValues
    20  // to omit any fields set to zero values.
    21  //
    22  // https://godoc.org/go.deanishe.net/env#DumpOption
    23  func (cfg *Config) From(v interface{}, opt ...env.DumpOption) error {
    24  	variables, err := env.Dump(v, opt...)
    25  	if err != nil {
    26  		return err
    27  	}
    28  
    29  	return cfg.setMulti(variables, false)
    30  }
    31  
    32  // setMulti batches the saving of multiple variables.
    33  func (cfg *Config) setMulti(variables map[string]string, export bool) error {
    34  	// sort keys to make the output testable
    35  	var keys []string
    36  	for k := range variables {
    37  		keys = append(keys, k)
    38  	}
    39  	sort.Strings(keys)
    40  
    41  	for _, k := range keys {
    42  		cfg.Set(k, variables[k], export)
    43  	}
    44  
    45  	return cfg.Do()
    46  }