github.com/theliebeskind/genfig@v0.1.5-alpha/plugins/write_to_env.go (about)

     1  package plugins
     2  
     3  import (
     4  	"io"
     5  	"strings"
     6  	"text/template"
     7  
     8  	"github.com/theliebeskind/genfig/models"
     9  )
    10  
    11  type writeToEnvPlugin struct {
    12  	s   models.SchemaMap
    13  	tpl *template.Template
    14  }
    15  
    16  var (
    17  	writeToEnv = writeToEnvPlugin{
    18  		s: models.SchemaMap{},
    19  		tpl: template.Must(template.
    20  			New("writeToEnv").
    21  			Funcs(template.FuncMap{
    22  				"upper":     strings.ToUpper,
    23  				"hasPrefix": strings.HasPrefix,
    24  				// Remove root (usually "Config_") from env var name
    25  				"cleanPrefixEnv": func(s string) string {
    26  					return strings.Join(strings.Split(s, "_")[1:], "_")
    27  				},
    28  				// Converte an env var name to a Config path
    29  				"makePath": func(s string) string {
    30  					return strings.Join(strings.Split(s, "_")[1:], ".")
    31  				},
    32  			}).
    33  			Parse(`import (
    34  	"fmt"
    35  	"os"
    36  	"encoding/json"
    37  )
    38  
    39  var (
    40  	_ = os.Setenv
    41  	_ = fmt.Sprintf
    42  	_ = json.Marshal
    43  )
    44  
    45  func (c *Config) WriteToEnv() {
    46  	var buf []byte
    47  	_ = buf
    48  {{range $_, $v := .}}{{if not $v.IsStruct}}
    49  	{{if hasPrefix $v.Content "[]"}}
    50  	buf, _ = json.Marshal(c.{{makePath $v.Path}})
    51  	_ = os.Setenv("{{cleanPrefixEnv (upper $v.Path)}}", string(buf))
    52  	{{else}}
    53  	_ = os.Setenv("{{cleanPrefixEnv (upper $v.Path)}}", fmt.Sprintf("%v", c.{{makePath $v.Path}}))
    54  	{{end}}
    55  {{end}}{{end}}
    56  }
    57  `))}
    58  )
    59  
    60  func init() {
    61  	// "register" plugin
    62  	Plugins["write_to_env"] = &writeToEnv
    63  }
    64  
    65  // GetInitCall returns the availibility and the string of the
    66  // function to be called on init
    67  func (p *writeToEnvPlugin) GetInitCall() (string, bool) {
    68  	return "", false
    69  }
    70  
    71  // SetSchemaMap sets the schema to be used when WriteTo is called
    72  func (p *writeToEnvPlugin) SetSchemaMap(s models.SchemaMap) {
    73  	p.s = s
    74  }
    75  
    76  // WriteTo performs the acutal writing to a buffer (or io.Writer).
    77  // For this plugin, the template is simply "rendered" into the writer.
    78  func (p *writeToEnvPlugin) WriteTo(w io.Writer) (l int64, err error) {
    79  	err = p.tpl.Execute(w, p.s)
    80  	return
    81  }