summaryrefslogtreecommitdiff
path: root/internal/cmd/config.go
blob: 431139a1b7fa474c7baad61236734157435c0ed6 (plain)
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
89
90
91
92
93
94
95
96
97
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package cmd

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"log/slog"
	"os"
	"time"

	"github.com/hairyhenderson/gomplate/v4"
	"github.com/hairyhenderson/gomplate/v4/conv"
	"github.com/hairyhenderson/gomplate/v4/env"
	"github.com/hairyhenderson/gomplate/v4/internal/datafs"

	"github.com/spf13/cobra"
)

const (
	defaultConfigFile = ".gomplate.yaml"
)

// loadConfig is intended to be called before command execution. It:
// - creates a gomplate.Config from the cobra flags
// - creates a gomplate.Config from the config file (if present)
// - merges the two (flags take precedence)
func loadConfig(ctx context.Context, cmd *cobra.Command, args []string) (*gomplate.Config, error) {
	flagConfig, err := cobraConfig(cmd, args)
	if err != nil {
		return nil, err
	}

	cfg, err := readConfigFile(ctx, cmd)
	if err != nil {
		return nil, err
	}
	if cfg == nil {
		cfg = flagConfig
	} else {
		cfg = cfg.MergeFrom(flagConfig)
	}

	cfg, err = applyEnvVars(ctx, cfg)
	if err != nil {
		return nil, err
	}

	cfg.Stdin = cmd.InOrStdin()
	cfg.Stdout = cmd.OutOrStdout()
	cfg.Stderr = cmd.ErrOrStderr()

	return cfg, nil
}

func pickConfigFile(cmd *cobra.Command) (cfgFile string, required bool) {
	cfgFile = defaultConfigFile
	if c := env.Getenv("GOMPLATE_CONFIG"); c != "" {
		cfgFile = c
		required = true
	}
	if cmd.Flags().Changed("config") && cmd.Flag("config").Value.String() != "" {
		// Use config file from the flag if specified
		cfgFile = cmd.Flag("config").Value.String()
		required = true
	}
	return cfgFile, required
}

func readConfigFile(ctx context.Context, cmd *cobra.Command) (*gomplate.Config, error) {
	cfgFile, configRequired := pickConfigFile(cmd)

	// we only support loading configs from the local filesystem for now
	fsys, err := datafs.FSysForPath(ctx, cfgFile)
	if err != nil {
		return nil, fmt.Errorf("fsys for path %v: %w", cfgFile, err)
	}

	f, err := fsys.Open(cfgFile)
	if err != nil {
		if configRequired {
			return nil, fmt.Errorf("config file requested, but couldn't be opened: %w", err)
		}
		return nil, nil
	}

	cfg, err := gomplate.Parse(f)
	if err != nil {
		return nil, fmt.Errorf("parsing config file %q: %w", cfgFile, err)
	}

	slog.DebugContext(ctx, "using config file", "cfgFile", cfgFile)

	return cfg, nil
}

// cobraConfig - initialize a config from the commandline options
func cobraConfig(cmd *cobra.Command, args []string) (cfg *gomplate.Config, err error) {
	cfg = &gomplate.Config{}
	cfg.InputFiles, err = getStringSlice(cmd, "file")
	if err != nil {
		return nil, err
	}
	cfg.Input, err = getString(cmd, "in")
	if err != nil {
		return nil, err
	}
	cfg.InputDir, err = getString(cmd, "input-dir")
	if err != nil {
		return nil, err
	}

	cfg.ExcludeGlob, err = getStringSlice(cmd, "exclude")
	if err != nil {
		return nil, err
	}
	cfg.ExcludeProcessingGlob, err = getStringSlice(cmd, "exclude-processing")
	if err != nil {
		return nil, err
	}

	includesFlag, err := getStringSlice(cmd, "include")
	if err != nil {
		return nil, err
	}
	// support --include
	cfg.ExcludeGlob = processIncludes(includesFlag, cfg.ExcludeGlob)

	cfg.OutputFiles, err = getStringSlice(cmd, "out")
	if err != nil {
		return nil, err
	}
	cfg.OutputDir, err = getString(cmd, "output-dir")
	if err != nil {
		return nil, err
	}
	cfg.OutputMap, err = getString(cmd, "output-map")
	if err != nil {
		return nil, err
	}
	cfg.OutMode, err = getString(cmd, "chmod")
	if err != nil {
		return nil, err
	}

	if len(args) > 0 {
		cfg.PostExec = args
	}

	cfg.ExecPipe, err = getBool(cmd, "exec-pipe")
	if err != nil {
		return nil, err
	}
	cfg.Experimental, err = getBool(cmd, "experimental")
	if err != nil {
		return nil, err
	}

	cfg.LDelim, err = getString(cmd, "left-delim")
	if err != nil {
		return nil, err
	}
	cfg.RDelim, err = getString(cmd, "right-delim")
	if err != nil {
		return nil, err
	}

	cfg.MissingKey, err = getString(cmd, "missing-key")
	if err != nil {
		return nil, err
	}

	ds, err := getStringSlice(cmd, "datasource")
	if err != nil {
		return nil, err
	}
	cx, err := getStringSlice(cmd, "context")
	if err != nil {
		return nil, err
	}
	ts, err := getStringSlice(cmd, "template")
	if err != nil {
		return nil, err
	}
	hdr, err := getStringSlice(cmd, "datasource-header")
	if err != nil {
		return nil, err
	}
	err = cfg.ParseDataSourceFlags(ds, cx, ts, hdr)
	if err != nil {
		return nil, err
	}

	pl, err := getStringSlice(cmd, "plugin")
	if err != nil {
		return nil, err
	}
	err = cfg.ParsePluginFlags(pl)
	if err != nil {
		return nil, err
	}
	return cfg, nil
}

func getStringSlice(cmd *cobra.Command, flag string) (s []string, err error) {
	if cmd.Flag(flag) != nil && cmd.Flag(flag).Changed {
		s, err = cmd.Flags().GetStringSlice(flag)
	}
	return s, err
}

func getString(cmd *cobra.Command, flag string) (s string, err error) {
	if cmd.Flag(flag) != nil && cmd.Flag(flag).Changed {
		s, err = cmd.Flags().GetString(flag)
	}
	return s, err
}

func getBool(cmd *cobra.Command, flag string) (b bool, err error) {
	if cmd.Flag(flag) != nil && cmd.Flag(flag).Changed {
		b, err = cmd.Flags().GetBool(flag)
	}
	return b, err
}

// process --include flags - these are analogous to specifying --exclude '*',
// then the inverse of the --include options.
func processIncludes(includes, excludes []string) []string {
	if len(includes) == 0 && len(excludes) == 0 {
		return nil
	}

	out := []string{}
	// if any --includes are set, we start by excluding everything
	if len(includes) > 0 {
		out = make([]string, 1+len(includes))
		out[0] = "*"
	}
	for i, include := range includes {
		// includes are just the opposite of an exclude
		out[i+1] = "!" + include
	}
	out = append(out, excludes...)
	return out
}

func applyEnvVars(_ context.Context, cfg *gomplate.Config) (*gomplate.Config, error) {
	if to := env.Getenv("GOMPLATE_PLUGIN_TIMEOUT"); cfg.PluginTimeout == 0 && to != "" {
		t, err := time.ParseDuration(to)
		if err != nil {
			return nil, fmt.Errorf("GOMPLATE_PLUGIN_TIMEOUT set to invalid value %q: %w", to, err)
		}
		cfg.PluginTimeout = t
	}

	if !cfg.Experimental && conv.ToBool(env.Getenv("GOMPLATE_EXPERIMENTAL", "false")) {
		cfg.Experimental = true
	}

	if cfg.LDelim == "" {
		cfg.LDelim = env.Getenv("GOMPLATE_LEFT_DELIM")
	}
	if cfg.RDelim == "" {
		cfg.RDelim = env.Getenv("GOMPLATE_RIGHT_DELIM")
	}

	return cfg, nil
}

// postExecInput - return the input to be used after the post-exec command. The
// input config may be modified if ExecPipe is set (OutputFiles is set to "-"),
// and Stdout is redirected to a pipe.
func postExecInput(cfg *gomplate.Config) io.Reader {
	if cfg.ExecPipe {
		pipe := &bytes.Buffer{}
		cfg.OutputFiles = []string{"-"}

		// --exec-pipe redirects standard out to the out pipe
		cfg.Stdout = pipe

		return pipe
	}

	if cfg.Stdin != nil {
		return cfg.Stdin
	}

	return os.Stdin
}