| 16 | const maxMessages = 10 |
| 17 | |
| 18 | func ParseTemplate(hookTemplate string, cmd *cobra.Command) ([]string, error) { |
| 19 | out := hookTemplate |
| 20 | if strings.Contains(hookTemplate, "{{") { |
| 21 | // Message may be a template. |
| 22 | msgContext := commandInfo{cmd: cmd} |
| 23 | |
| 24 | tmpl, err := template.New("").Funcs(template.FuncMap{ |
| 25 | "command": msgContext.command, |
| 26 | "flagValue": msgContext.flagValue, |
| 27 | "argValue": msgContext.argValue, |
| 28 | |
| 29 | // kept for backward-compatibility with old templates. |
| 30 | "flag": func(_ any, flagName string) (string, error) { return msgContext.flagValue(flagName) }, |
| 31 | "arg": func(_ any, i int) (string, error) { return msgContext.argValue(i) }, |
| 32 | }).Parse(hookTemplate) |
| 33 | if err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 | var b bytes.Buffer |
| 37 | err = tmpl.Execute(&b, msgContext) |
| 38 | if err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 | out = b.String() |
| 42 | } |
| 43 | if n := strings.Count(out, "\n"); n > maxMessages { |
| 44 | return nil, fmt.Errorf("hook template contains too many messages (%d): maximum is %d", n, maxMessages) |
| 45 | } |
| 46 | return strings.SplitN(out, "\n", maxMessages), nil |
| 47 | } |
| 48 | |
| 49 | var ErrHookTemplateParse = errors.New("failed to parse hook template") |
| 50 | |