2018-02-05 16:05:59 -05:00
package templates // import "github.com/docker/docker/daemon/logger/templates"
2016-03-04 12:29:44 -05:00
import (
2017-03-27 12:50:53 -04:00
"bytes"
2016-03-04 12:29:44 -05:00
"encoding/json"
"strings"
"text/template"
)
// basicFunctions are the set of initial
// functions provided to every template.
var basicFunctions = template . FuncMap {
"json" : func ( v interface { } ) string {
2017-03-27 12:50:53 -04:00
buf := & bytes . Buffer { }
enc := json . NewEncoder ( buf )
enc . SetEscapeHTML ( false )
enc . Encode ( v )
// Remove the trailing new line added by the encoder
return strings . TrimSpace ( buf . String ( ) )
2016-03-04 12:29:44 -05:00
} ,
2017-01-26 15:49:40 -05:00
"split" : strings . Split ,
"join" : strings . Join ,
2022-01-31 10:07:40 -05:00
"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.
2017-01-26 15:49:40 -05:00
"lower" : strings . ToLower ,
"upper" : strings . ToUpper ,
"pad" : padWithSpace ,
"truncate" : truncateWithLength ,
2016-03-04 12:29:44 -05:00
}
// NewParse creates a new tagged template with the basic functions
// and parses the given format.
func NewParse ( tag , format string ) ( * template . Template , error ) {
return template . New ( tag ) . Funcs ( basicFunctions ) . Parse ( format )
}
2016-09-13 14:21:07 -04:00
// padWithSpace adds whitespace to the input if the input is non-empty
func padWithSpace ( source string , prefix , suffix int ) string {
if source == "" {
return source
}
return strings . Repeat ( " " , prefix ) + source + strings . Repeat ( " " , suffix )
}
2017-01-26 15:49:40 -05:00
// truncateWithLength truncates the source string up to the length provided by the input
func truncateWithLength ( source string , length int ) string {
if len ( source ) < length {
return source
}
return source [ : length ]
}