github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/formatter/context.go (about) 1 package formatter 2 3 const ( 4 // ClientContextTableFormat is the default client context format. 5 ClientContextTableFormat = "table {{.Name}}{{if .Current}} *{{end}}\t{{.Description}}\t{{.DockerEndpoint}}\t{{.Error}}" 6 7 dockerEndpointHeader = "DOCKER ENDPOINT" 8 quietContextFormat = "{{.Name}}" 9 10 maxErrLength = 45 11 ) 12 13 // NewClientContextFormat returns a Format for rendering using a Context 14 func NewClientContextFormat(source string, quiet bool) Format { 15 if quiet { 16 return quietContextFormat 17 } 18 if source == TableFormatKey { 19 return ClientContextTableFormat 20 } 21 return Format(source) 22 } 23 24 // ClientContext is a context for display 25 type ClientContext struct { 26 Name string 27 Description string 28 DockerEndpoint string 29 Current bool 30 Error string 31 } 32 33 // ClientContextWrite writes formatted contexts using the Context 34 func ClientContextWrite(ctx Context, contexts []*ClientContext) error { 35 render := func(format func(subContext SubContext) error) error { 36 for _, context := range contexts { 37 if err := format(&clientContextContext{c: context}); err != nil { 38 return err 39 } 40 } 41 return nil 42 } 43 return ctx.Write(newClientContextContext(), render) 44 } 45 46 type clientContextContext struct { 47 HeaderContext 48 c *ClientContext 49 } 50 51 func newClientContextContext() *clientContextContext { 52 ctx := clientContextContext{} 53 ctx.Header = SubHeaderContext{ 54 "Name": NameHeader, 55 "Description": DescriptionHeader, 56 "DockerEndpoint": dockerEndpointHeader, 57 "Error": ErrorHeader, 58 } 59 return &ctx 60 } 61 62 func (c *clientContextContext) MarshalJSON() ([]byte, error) { 63 return MarshalJSON(c) 64 } 65 66 func (c *clientContextContext) Current() bool { 67 return c.c.Current 68 } 69 70 func (c *clientContextContext) Name() string { 71 return c.c.Name 72 } 73 74 func (c *clientContextContext) Description() string { 75 return c.c.Description 76 } 77 78 func (c *clientContextContext) DockerEndpoint() string { 79 return c.c.DockerEndpoint 80 } 81 82 // Error returns the truncated error (if any) that occurred when loading the context. 83 func (c *clientContextContext) Error() string { 84 // TODO(thaJeztah) add "--no-trunc" option to context ls and set default to 30 cols to match "docker service ps" 85 return Ellipsis(c.c.Error, maxErrLength) 86 } 87 88 // KubernetesEndpoint returns the kubernetes endpoint. 89 // 90 // Deprecated: support for kubernetes endpoints in contexts has been removed, and this formatting option will always be empty. 91 func (c *clientContextContext) KubernetesEndpoint() string { 92 return "" 93 }