From 3d3db0d4af6cf483299a152133f19f9df760dc11 Mon Sep 17 00:00:00 2001 From: David Calavera Date: Wed, 5 Aug 2015 13:00:20 -0700 Subject: [PATCH] Fail fail when the ps format template is invalid. Fixes error continuing execution when the parsing fails. Signed-off-by: David Calavera --- api/client/ps/custom.go | 11 +++++++---- api/client/ps/custom_test.go | 16 +++++++++++++++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/api/client/ps/custom.go b/api/client/ps/custom.go index d9e8fe0758..6d2518b5b2 100644 --- a/api/client/ps/custom.go +++ b/api/client/ps/custom.go @@ -170,9 +170,11 @@ func customFormat(ctx Context, containers []types.Container) { format += "\t{{.Size}}" } - tmpl, err := template.New("ps template").Parse(format) + tmpl, err := template.New("").Parse(format) if err != nil { - buffer.WriteString(fmt.Sprintf("Invalid `docker ps` format: %v\n", err)) + buffer.WriteString(fmt.Sprintf("Template parsing error: %v\n", err)) + buffer.WriteTo(ctx.Output) + return } for _, container := range containers { @@ -181,8 +183,9 @@ func customFormat(ctx Context, containers []types.Container) { c: container, } if err := tmpl.Execute(buffer, containerCtx); err != nil { - buffer = bytes.NewBufferString(fmt.Sprintf("Invalid `docker ps` format: %v\n", err)) - break + buffer = bytes.NewBufferString(fmt.Sprintf("Template parsing error: %v\n", err)) + buffer.WriteTo(ctx.Output) + return } if table && len(header) == 0 { header = containerCtx.fullHeader() diff --git a/api/client/ps/custom_test.go b/api/client/ps/custom_test.go index 8676518e57..706b86dc01 100644 --- a/api/client/ps/custom_test.go +++ b/api/client/ps/custom_test.go @@ -1,6 +1,7 @@ package ps import ( + "bytes" "reflect" "strings" "testing" @@ -10,7 +11,7 @@ import ( "github.com/docker/docker/pkg/stringid" ) -func TestContainerContextID(t *testing.T) { +func TestContainerPsContext(t *testing.T) { containerID := stringid.GenerateRandomID() unix := time.Now().Unix() @@ -86,3 +87,16 @@ func TestContainerContextID(t *testing.T) { } } + +func TestContainerPsFormatError(t *testing.T) { + out := bytes.NewBufferString("") + ctx := Context{ + Format: "{{InvalidFunction}}", + Output: out, + } + + customFormat(ctx, make([]types.Container, 0)) + if out.String() != "Template parsing error: template: :1: function \"InvalidFunction\" not defined\n" { + t.Fatalf("Expected format error, got `%v`\n", out.String()) + } +}