github.com/sudo-bmitch/version-bump@v0.0.0-20240503123857-70b0e3f646dd/internal/source/custom.go (about) 1 package source 2 3 import ( 4 "fmt" 5 "os/exec" 6 "strings" 7 8 "github.com/sudo-bmitch/version-bump/internal/config" 9 ) 10 11 const ( 12 customCmd = "cmd" 13 ) 14 15 type custom struct { 16 conf config.Source 17 } 18 19 func newCustom(conf config.Source) Source { 20 return custom{conf: conf} 21 } 22 23 func (c custom) Get(data config.SourceTmplData) (string, error) { 24 confExp, err := c.conf.ExpandTemplate(data) 25 if err != nil { 26 return "", fmt.Errorf("failed to expand template: %w", err) 27 } 28 // TODO: add support for exec, bypassing the shell, which means arg values need to also support arrays 29 if _, ok := confExp.Args[customCmd]; !ok { 30 return "", fmt.Errorf("custom source requires a cmd arg") 31 } 32 out, err := exec.Command("/bin/sh", "-c", confExp.Args[customCmd]).Output() 33 if err != nil { 34 return "", fmt.Errorf("failed running %s: %w", confExp.Args[customCmd], err) 35 } 36 verData := VersionTmplData{ 37 Version: strings.TrimSpace(string(out)), 38 } 39 return procResult(confExp, verData) 40 } 41 42 func (c custom) Key(data config.SourceTmplData) (string, error) { 43 confExp, err := c.conf.ExpandTemplate(data) 44 if err != nil { 45 return "", fmt.Errorf("failed to expand template: %w", err) 46 } 47 return confExp.Key, nil 48 }