Add format functions

Add functions to go templates such as truncating a field.  Also add
the table keyword, which, if placed at the beginning of a format string,
adds headers to the output

Signed-off-by: Ryan Cole <rcyoalne@gmail.com>
This commit is contained in:
Ryan Cole 2017-08-15 16:53:17 -04:00
parent 6ca462a3b6
commit 08c3d241a4
10 changed files with 298 additions and 1046 deletions

View file

@ -1,8 +1,11 @@
package main
import (
"strings"
is "github.com/containers/image/storage"
"github.com/containers/storage"
"github.com/fatih/camelcase"
"github.com/kubernetes-incubator/cri-o/libkpod"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
@ -53,3 +56,8 @@ func getConfig(c *cli.Context) (*libkpod.Config, error) {
return config, nil
}
func splitCamelCase(src string) string {
entries := camelcase.Split(src)
return strings.Join(entries, " ")
}

View file

@ -3,9 +3,11 @@ package formats
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"os"
"strings"
"text/template"
"github.com/pkg/errors"
)
// Writer interface for outputs
@ -22,6 +24,7 @@ type JSONstruct struct {
type StdoutTemplate struct {
Output []interface{}
Template string
Fields map[string]string
}
// Out method for JSON
@ -36,14 +39,23 @@ func (j JSONstruct) Out() error {
// Out method for Go templates
func (t StdoutTemplate) Out() error {
tmpl, err := template.New("image").Parse(t.Template)
if strings.HasPrefix(t.Template, "table") {
t.Template = strings.TrimSpace(t.Template[5:])
headerTmpl, err := template.New("header").Funcs(headerFunctions).Parse(t.Template)
if err != nil {
errors.Wrapf(err, "Template parsing error")
}
err = headerTmpl.Execute(os.Stdout, t.Fields)
fmt.Println()
}
tmpl, err := template.New("image").Funcs(basicFunctions).Parse(t.Template)
if err != nil {
return errors.Wrapf(err, "Template parsing error")
}
for _, img := range t.Output {
err = tmpl.Execute(os.Stdout, img)
basicTmpl := tmpl.Funcs(basicFunctions)
err = basicTmpl.Execute(os.Stdout, img)
if err != nil {
return err
}

View file

@ -0,0 +1,78 @@
package formats
import (
"bytes"
"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 {
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())
},
"split": strings.Split,
"join": strings.Join,
"title": strings.Title,
"lower": strings.ToLower,
"upper": strings.ToUpper,
"pad": padWithSpace,
"truncate": truncateWithLength,
}
// HeaderFunctions are used to created headers of a table.
// This is a replacement of basicFunctions for header generation
// because we want the header to remain intact.
// Some functions like `split` are irrevelant so not added.
var headerFunctions = template.FuncMap{
"json": func(v string) string {
return v
},
"title": func(v string) string {
return v
},
"lower": func(v string) string {
return v
},
"upper": func(v string) string {
return v
},
"truncate": func(v string, l int) string {
return v
},
}
// Parse creates a new anonymous template with the basic functions
// and parses the given format.
func Parse(format string) (*template.Template, error) {
return NewParse("", format)
}
// 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)
}
// 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)
}
// 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]
}

View file

@ -2,6 +2,9 @@ package main
import (
"fmt"
"reflect"
"strings"
"github.com/containers/storage"
"github.com/kubernetes-incubator/cri-o/cmd/kpod/formats"
libkpodimage "github.com/kubernetes-incubator/cri-o/libkpod/image"
@ -10,14 +13,6 @@ import (
"github.com/urfave/cli"
)
type imageOutputParams struct {
ID string `json:"id"`
Name string `json:"names"`
Digest digest.Digest `json:"digest"`
CreatedAt string `json:"created"`
Size string `json:"size"`
}
var (
imagesFlags = []cli.Flag{
cli.BoolFlag{
@ -201,9 +196,7 @@ func outputImages(store storage.Store, images []storage.Image, truncate, digests
case "json":
out = formats.JSONstruct{Output: toGeneric(imageOutput)}
default:
// Assuming Go-template
out = formats.StdoutTemplate{Output: toGeneric(imageOutput), Template: outputFormat}
out = formats.StdoutTemplate{Output: toGeneric(imageOutput), Template: outputFormat, Fields: imageOutput[0].headerMap()}
}
} else {
out = stdoutstruct{output: imageOutput, digests: digests, truncate: truncate, quiet: quiet, noheading: noheading}
@ -213,3 +206,26 @@ func outputImages(store storage.Store, images []storage.Image, truncate, digests
return nil
}
type imageOutputParams struct {
ID string `json:"id"`
Name string `json:"names"`
Digest digest.Digest `json:"digest"`
CreatedAt string `json:"created"`
Size string `json:"size"`
}
func (i *imageOutputParams) headerMap() map[string]string {
v := reflect.Indirect(reflect.ValueOf(i))
values := make(map[string]string)
for i := 0; i < v.NumField(); i++ {
key := v.Type().Field(i).Name
value := key
if value == "ID" || value == "Name" {
value = "Image" + value
}
values[key] = fmt.Sprintf("%s ", strings.ToUpper(splitCamelCase(value)))
}
return values
}