github.com/panekj/cli@v0.0.0-20230304125325-467dd2f3797e/cli/command/stack/formatter/formatter.go (about) 1 package formatter 2 3 import ( 4 "strconv" 5 6 "github.com/docker/cli/cli/command/formatter" 7 ) 8 9 const ( 10 // SwarmStackTableFormat is the default Swarm stack format 11 SwarmStackTableFormat formatter.Format = "table {{.Name}}\t{{.Services}}" 12 13 stackServicesHeader = "SERVICES" 14 15 // TableFormatKey is an alias for formatter.TableFormatKey 16 TableFormatKey = formatter.TableFormatKey 17 ) 18 19 // Context is an alias for formatter.Context 20 type Context = formatter.Context 21 22 // Format is an alias for formatter.Format 23 type Format = formatter.Format 24 25 // Stack contains deployed stack information. 26 type Stack struct { 27 // Name is the name of the stack 28 Name string 29 // Services is the number of the services 30 Services int 31 } 32 33 // StackWrite writes formatted stacks using the Context 34 func StackWrite(ctx formatter.Context, stacks []*Stack) error { 35 render := func(format func(subContext formatter.SubContext) error) error { 36 for _, stack := range stacks { 37 if err := format(&stackContext{s: stack}); err != nil { 38 return err 39 } 40 } 41 return nil 42 } 43 return ctx.Write(newStackContext(), render) 44 } 45 46 type stackContext struct { 47 formatter.HeaderContext 48 s *Stack 49 } 50 51 func newStackContext() *stackContext { 52 stackCtx := stackContext{} 53 stackCtx.Header = formatter.SubHeaderContext{ 54 "Name": formatter.NameHeader, 55 "Services": stackServicesHeader, 56 } 57 return &stackCtx 58 } 59 60 func (s *stackContext) MarshalJSON() ([]byte, error) { 61 return formatter.MarshalJSON(s) 62 } 63 64 func (s *stackContext) Name() string { 65 return s.s.Name 66 } 67 68 func (s *stackContext) Services() string { 69 return strconv.Itoa(s.s.Services) 70 }