forked from twpayne/chezmoi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secret_generic.go
75 lines (65 loc) · 2.08 KB
/
secret_generic.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
package cmd
import (
"encoding/json"
"fmt"
"os/exec"
"strings"
"github.com/spf13/cobra"
"github.com/twpayne/chezmoi/lib/chezmoi"
vfs "github.com/twpayne/go-vfs"
)
var genericSecretCmd = &cobra.Command{
Use: "generic [args...]",
Short: "Execute a generic secret command",
RunE: makeRunE(config.runGenericSecretCmd),
}
type genericSecretCmdConfig struct {
Command string
}
var genericSecretCache = make(map[string][]byte)
func init() {
config.addTemplateFunc("secret", config.secretFunc)
config.addTemplateFunc("secretJSON", config.secretJSONFunc)
secretCmd.AddCommand(genericSecretCmd)
}
func (c *Config) runGenericSecretCmd(fs vfs.FS, args []string) error {
return c.exec(append([]string{c.GenericSecret.Command}, args...))
}
func (c *Config) secretFunc(args ...string) interface{} {
// FIXME factor out common functionality with secretJSONFunc
key := strings.Join(args, "\x00")
if output, ok := genericSecretCache[key]; ok {
return output
}
name := c.GenericSecret.Command
if c.Verbose {
fmt.Printf("%s %s\n", name, strings.Join(args, " "))
}
output, err := exec.Command(name, args...).CombinedOutput()
if err != nil {
chezmoi.ReturnTemplateFuncError(fmt.Errorf("secret: %s %s: %v\n%s", name, strings.Join(args, " "), err, output))
}
genericSecretCache[key] = output
return strings.TrimSpace(string(output))
}
func (c *Config) secretJSONFunc(args ...string) interface{} {
// FIXME factor out common functionality with secretFunc
key := strings.Join(args, "\x00")
if output, ok := genericSecretCache[key]; ok {
return output
}
name := c.GenericSecret.Command
if c.Verbose {
fmt.Printf("%s %s\n", name, strings.Join(args, " "))
}
output, err := exec.Command(name, args...).CombinedOutput()
if err != nil {
chezmoi.ReturnTemplateFuncError(fmt.Errorf("secretJSON: %s %s: %v\n%s", name, strings.Join(args, " "), err, output))
}
var data interface{}
if err := json.Unmarshal(output, &data); err != nil {
chezmoi.ReturnTemplateFuncError(fmt.Errorf("secretJSON: %s %s: %v\n%s", name, strings.Join(args, " "), err, output))
}
genericSecretCache[key] = output
return data
}