github.com/blend/go-sdk@v1.20220411.3/template/viewmodel.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package template 9 10 import ( 11 "fmt" 12 "os" 13 14 "github.com/blend/go-sdk/env" 15 ) 16 17 // Viewmodel is the template viewmodel. 18 // It surfaces a subset of the template api. 19 // It is set / accessed by the outer template. 20 type Viewmodel struct { 21 vars Vars 22 env env.Vars 23 } 24 25 // Vars returns the vars collection. 26 func (vm Viewmodel) Vars() Vars { 27 return vm.vars 28 } 29 30 // Var returns the value of a variable, or panics if the variable is not set. 31 func (vm Viewmodel) Var(key string, defaults ...interface{}) (interface{}, error) { 32 if value, hasVar := vm.vars[key]; hasVar { 33 return value, nil 34 } 35 36 if len(defaults) > 0 { 37 return defaults[0], nil 38 } 39 40 return nil, fmt.Errorf("template variable `%s` is unset and no default is provided", key) 41 } 42 43 // Has is an alias to `HasVar`. 44 func (vm Viewmodel) Has(key string) bool { 45 return vm.HasVar(key) 46 } 47 48 // HasVar returns if a variable is set. 49 func (vm Viewmodel) HasVar(key string) bool { 50 _, hasKey := vm.vars[key] 51 return hasKey 52 } 53 54 // Env returns an environment variable. 55 func (vm Viewmodel) Env(key string, defaults ...string) (string, error) { 56 if value, hasVar := vm.env[key]; hasVar { 57 return value, nil 58 } 59 60 if len(defaults) > 0 { 61 return defaults[0], nil 62 } 63 return "", fmt.Errorf("template environment variable `%s` is unset and no default is provided", key) 64 } 65 66 // HasEnv returns if an env var is set. 67 func (vm Viewmodel) HasEnv(key string) bool { 68 _, hasKey := vm.env[key] 69 return hasKey 70 } 71 72 // ExpandEnv replaces $var or ${var} based on the configured environment variables. 73 func (vm Viewmodel) ExpandEnv(s string) string { 74 return os.Expand(s, func(key string) string { 75 if value, ok := vm.env[key]; ok { 76 return value 77 } 78 return "" 79 }) 80 }