Files
kopia/notification/notifytemplate/embeddedtemplate.go
Jarek Kowalski c0bd372d29 feat(cli): support for defining notification profiles and templates via CLI (#4034)
* feat(cli): support for defining notification profiles via CLI

Profile management:

```
$ kopia notification profile configure email \
    --profile-name=X \
    --smtp-server=smtp.gmail.com \
    --smtp-port=587 \
    --smtp-username=X \
    --smtp-password=X \
    --mail-from=X \
    --mail-to=X \
    --format=html|txt \
    [--send-test-notification]

$ kopia notification profile configure pushover --profile-name=X \
    --user-key=X \
    --app-token=X \
    --format=html|txt \
    [--send-test-notification]

$ kopia notification profile configure webhook --profile-name=X \
    --endpooint=http://some-address:port/path \
    --method=POST|PUT \
    --format=html|txt \
    [--send-test-notification]

$ kopia notification profile test --profile-name=X

$ kopia notification profile delete --profile-name=X

$ kopia notification profile list
```

Template management:

```
$ kopia notification template show X

$ kopia notification template set X \
   --from-stdin | --from-file=X | --editor

$ kopia notification template remove X

$ kopia notification template list

```

Implements #1958

* additional refactoring for testability, various naming tweaks
2024-10-06 16:28:39 +00:00

68 lines
1.3 KiB
Go

// Package notifytemplate provides a way to access notification templates.
package notifytemplate
import (
"embed"
"text/template"
"time"
"github.com/pkg/errors"
"github.com/kopia/kopia/fs"
)
//go:embed "*.html"
//go:embed "*.txt"
var embedded embed.FS
// Template names.
const (
TestNotification = "test-notification"
)
// Functions is a map of functions that can be used in templates.
//
//nolint:gochecknoglobals
var Functions = template.FuncMap{
"toTime": func(t any) time.Time {
if t, ok := t.(time.Time); ok {
return t
}
if t, ok := t.(fs.UTCTimestamp); ok {
return t.ToTime()
}
return time.Time{}
},
}
// GetEmbeddedTemplate returns embedded template by name.
func GetEmbeddedTemplate(templateName string) (string, error) {
b, err := embedded.ReadFile(templateName)
if err != nil {
return "", errors.Wrap(err, "unable to read embedded template")
}
return string(b), nil
}
// SupportedTemplates returns a list of supported template names.
func SupportedTemplates() []string {
var s []string
entries, _ := embedded.ReadDir(".")
for _, e := range entries {
s = append(s, e.Name())
}
return s
}
// ParseTemplate parses a named template.
func ParseTemplate(tmpl string) (*template.Template, error) {
//nolint:wrapcheck
return template.New("template").Funcs(Functions).Parse(tmpl)
}