templates.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package templates // import "github.com/docker/docker/daemon/logger/templates"
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "strings"
  6. "text/template"
  7. )
  8. // basicFunctions are the set of initial
  9. // functions provided to every template.
  10. var basicFunctions = template.FuncMap{
  11. "json": func(v interface{}) string {
  12. buf := &bytes.Buffer{}
  13. enc := json.NewEncoder(buf)
  14. enc.SetEscapeHTML(false)
  15. enc.Encode(v)
  16. // Remove the trailing new line added by the encoder
  17. return strings.TrimSpace(buf.String())
  18. },
  19. "split": strings.Split,
  20. "join": strings.Join,
  21. "title": strings.Title, //nolint:staticcheck // SA1019: strings.Title is deprecated: The rule Title uses for word boundaries does not handle Unicode punctuation properly. Use golang.org/x/text/cases instead.
  22. "lower": strings.ToLower,
  23. "upper": strings.ToUpper,
  24. "pad": padWithSpace,
  25. "truncate": truncateWithLength,
  26. }
  27. // NewParse creates a new tagged template with the basic functions
  28. // and parses the given format.
  29. func NewParse(tag, format string) (*template.Template, error) {
  30. return template.New(tag).Funcs(basicFunctions).Parse(format)
  31. }
  32. // padWithSpace adds whitespace to the input if the input is non-empty
  33. func padWithSpace(source string, prefix, suffix int) string {
  34. if source == "" {
  35. return source
  36. }
  37. return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix)
  38. }
  39. // truncateWithLength truncates the source string up to the length provided by the input
  40. func truncateWithLength(source string, length int) string {
  41. if len(source) < length {
  42. return source
  43. }
  44. return source[:length]
  45. }