This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
variable_reader.go
88 lines (72 loc) · 2.25 KB
/
variable_reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package secrethub
import (
"fmt"
"strings"
"github.com/secrethub/secrethub-cli/internals/cli/validation"
"github.com/secrethub/secrethub-cli/internals/cli/ui"
"github.com/secrethub/secrethub-cli/internals/secrethub/tpl"
)
type variableReader struct {
vars map[string]string
}
// newVariableReader returns a new template variable reader that fetches template variables from the
// specified OS environment variables and commandFlags. An error is returned if any of the provided variable
// names is invalid.
func newVariableReader(osEnv map[string]string, commandTemplateVars map[string]string) (tpl.VariableReader, error) {
templateVars := make(map[string]string)
for k, v := range osEnv {
if strings.HasPrefix(k, templateVarEnvVarPrefix) {
k = strings.TrimPrefix(k, templateVarEnvVarPrefix)
templateVars[strings.ToLower(k)] = v
}
}
for k, v := range commandTemplateVars {
templateVars[strings.ToLower(k)] = v
}
for k := range templateVars {
if !validation.IsEnvarNamePosix(k) {
return nil, ErrInvalidTemplateVar(k)
}
}
return &variableReader{
vars: templateVars,
}, nil
}
// ReadVariable fetches a template variable by name and errors if it is not found.
func (v *variableReader) ReadVariable(name string) (string, error) {
variable, ok := v.vars[name]
if !ok {
return "", tpl.ErrTemplateVarNotFound(name)
}
return variable, nil
}
type promptMissingVariableReader struct {
reader tpl.VariableReader
io ui.IO
answers map[string]string
}
func newPromptMissingVariableReader(reader tpl.VariableReader, io ui.IO) tpl.VariableReader {
return &promptMissingVariableReader{
reader: reader,
io: io,
answers: map[string]string{},
}
}
// ReadVariable fetches a template variable and prompts the user if it is not found.
func (p *promptMissingVariableReader) ReadVariable(name string) (string, error) {
variable, err := p.reader.ReadVariable(name)
if err != tpl.ErrTemplateVarNotFound(name) {
return variable, err
}
variable, ok := p.answers[name]
if ok {
return variable, nil
}
question := fmt.Sprintf("What is the value of the \"%s\" template variable?\n", name)
variable, err = ui.Ask(p.io, question)
if err != nil {
return "", tpl.ErrTemplateVarNotFound(name)
}
p.answers[name] = variable
return variable, err
}