prototype_preview.go 5.25 KB
Newer Older
bryanl's avatar
bryanl committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Copyright 2018 The ksonnet authors
//
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

package actions

import (
	"fmt"
	"io"
	"os"
	"strings"

bryanl's avatar
bryanl committed
24
	"github.com/ksonnet/ksonnet/pkg/app"
bryanl's avatar
bryanl committed
25
	"github.com/ksonnet/ksonnet/pkg/ksonnet"
bryanl's avatar
bryanl committed
26
	"github.com/ksonnet/ksonnet/pkg/pkg"
bryanl's avatar
bryanl committed
27
28
29
	"github.com/ksonnet/ksonnet/pkg/prototype"
	"github.com/ksonnet/ksonnet/pkg/prototype/snippet"
	"github.com/ksonnet/ksonnet/pkg/prototype/snippet/jsonnet"
bryanl's avatar
bryanl committed
30
	strutil "github.com/ksonnet/ksonnet/pkg/util/strings"
bryanl's avatar
bryanl committed
31
32
33
34
35
	"github.com/pkg/errors"
	"github.com/spf13/pflag"
)

// RunPrototypePreview runs `prototype describe`
bryanl's avatar
bryanl committed
36
37
func RunPrototypePreview(m map[string]interface{}) error {
	pp, err := NewPrototypePreview(m)
bryanl's avatar
bryanl committed
38
39
40
41
42
43
44
45
46
	if err != nil {
		return err
	}

	return pp.Run()
}

// PrototypePreview lists available namespaces
type PrototypePreview struct {
bryanl's avatar
bryanl committed
47
48
49
50
51
	app             app.App
	out             io.Writer
	query           string
	args            []string
	appPrototypesFn func(app.App, pkg.Descriptor) (prototype.SpecificationSchemas, error)
bryanl's avatar
bryanl committed
52
53
54
}

// NewPrototypePreview creates an instance of PrototypePreview
bryanl's avatar
bryanl committed
55
56
57
func NewPrototypePreview(m map[string]interface{}) (*PrototypePreview, error) {
	ol := newOptionLoader(m)

bryanl's avatar
bryanl committed
58
	pp := &PrototypePreview{
bryanl's avatar
bryanl committed
59
60
61
		app:   ol.LoadApp(),
		query: ol.LoadString(OptionQuery),
		args:  ol.LoadStringSlice(OptionArguments),
bryanl's avatar
bryanl committed
62
63
64
65
66
67
68

		out:             os.Stdout,
		appPrototypesFn: pkg.LoadPrototypes,
	}

	if ol.err != nil {
		return nil, ol.err
bryanl's avatar
bryanl committed
69
70
71
72
73
74
75
	}

	return pp, nil
}

// Run runs the env list action.
func (pp *PrototypePreview) Run() error {
bryanl's avatar
bryanl committed
76
	prototypes, err := allPrototypes(pp.app, pp.appPrototypesFn)
bryanl's avatar
bryanl committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
	if err != nil {
		return err
	}

	index := prototype.NewIndex(prototypes)

	prototypes, err = index.List()
	if err != nil {
		return err
	}

	p, err := findUniquePrototype(pp.query, prototypes)
	if err != nil {
		return err
	}

	flags := bindPrototypeParams(p)
	if err = flags.Parse(pp.args); err != nil {
95
96
97
		if strings.Contains(err.Error(), "help request") {
			return nil
		}
bryanl's avatar
bryanl committed
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
		return errors.Wrap(err, "parse preview args")
	}

	// NOTE: only supporting jsonnet templates
	templateType := prototype.Jsonnet

	params, err := getParameters(p, flags)
	if err != nil {
		return err
	}

	text, err := expandPrototype(p, templateType, params, "preview")
	if err != nil {
		return err
	}

	fmt.Fprintln(pp.out, text)
	return nil
}

func bindPrototypeParams(p *prototype.SpecificationSchema) *pflag.FlagSet {
	fs := pflag.NewFlagSet("preview", pflag.ContinueOnError)

	for _, param := range p.RequiredParams() {
		fs.String(param.Name, "", param.Description)
	}

	for _, param := range p.OptionalParams() {
		fs.String(param.Name, *param.Default, param.Description)
	}

	return fs
}

func getParameters(proto *prototype.SpecificationSchema, flags *pflag.FlagSet) (map[string]string, error) {
	missingRequired := prototype.ParamSchemas{}
	values := map[string]string{}
	for _, param := range proto.RequiredParams() {
		val, err := flags.GetString(param.Name)
		if err != nil {
			return nil, err
		} else if val == "" {
			missingRequired = append(missingRequired, param)
		} else if _, ok := values[param.Name]; ok {
			return nil, errors.Errorf("Prototype '%s' has multiple parameters with name '%s'", proto.Name, param.Name)
		}

		quoted, err := param.Quote(val)
		if err != nil {
			return nil, err
		}
		values[param.Name] = quoted
	}

	if len(missingRequired) > 0 {
		return nil, errors.Errorf("failed to instantiate prototype '%s'. The following required parameters are missing:\n%s", proto.Name, missingRequired.PrettyString(""))
	}

	for _, param := range proto.OptionalParams() {
		val, err := flags.GetString(param.Name)
		if err != nil {
			return nil, err
		} else if _, ok := values[param.Name]; ok {
			return nil, errors.Errorf("prototype '%s' has multiple parameters with name '%s'", proto.Name, param.Name)
		}

		quoted, err := param.Quote(val)
		if err != nil {
			return nil, err
		}
		values[param.Name] = quoted
	}

	return values, nil
}

// TODO: this doesn't belong here. Needs to be closer to where other jsonnet processing happens.
func expandPrototype(proto *prototype.SpecificationSchema, templateType prototype.TemplateType, params map[string]string, componentName string) (string, error) {
	template, err := proto.Template.Body(templateType)
	if err != nil {
		return "", err
	}
	if templateType == prototype.Jsonnet {
		componentsText := "components." + componentName
		if !strutil.IsASCIIIdentifier(componentName) {
			componentsText = fmt.Sprintf(`components["%s"]`, componentName)
		}
		template = append([]string{
bryanl's avatar
bryanl committed
186
187
			`local env = std.extVar("` + ksonnet.EnvExtCodeKey + `");`,
			`local params = std.extVar("` + ksonnet.ParamsExtCodeKey + `").` + componentsText + ";"},
bryanl's avatar
bryanl committed
188
189
190
191
192
193
194
			template...)
		return jsonnet.Parse(componentName, strings.Join(template, "\n"))
	}

	tm := snippet.Parse(strings.Join(template, "\n"))
	return tm.Evaluate(params)
}