github.com/sld880311/docker@v0.0.0-20200524143708-d5593973a475/cli/command/formatter/network.go (about) 1 package formatter 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/docker/docker/api/types" 8 "github.com/docker/docker/pkg/stringid" 9 ) 10 11 const ( 12 defaultNetworkTableFormat = "table {{.ID}}\t{{.Name}}\t{{.Driver}}\t{{.Scope}}" 13 14 networkIDHeader = "NETWORK ID" 15 ipv6Header = "IPV6" 16 internalHeader = "INTERNAL" 17 ) 18 19 // NewNetworkFormat returns a Format for rendering using a network Context 20 func NewNetworkFormat(source string, quiet bool) Format { 21 switch source { 22 case TableFormatKey: 23 if quiet { 24 return defaultQuietFormat 25 } 26 return defaultNetworkTableFormat 27 case RawFormatKey: 28 if quiet { 29 return `network_id: {{.ID}}` 30 } 31 return `network_id: {{.ID}}\nname: {{.Name}}\ndriver: {{.Driver}}\nscope: {{.Scope}}\n` 32 } 33 return Format(source) 34 } 35 36 // NetworkWrite writes the context 37 func NetworkWrite(ctx Context, networks []types.NetworkResource) error { 38 render := func(format func(subContext subContext) error) error { 39 for _, network := range networks { 40 networkCtx := &networkContext{trunc: ctx.Trunc, n: network} 41 if err := format(networkCtx); err != nil { 42 return err 43 } 44 } 45 return nil 46 } 47 return ctx.Write(&networkContext{}, render) 48 } 49 50 type networkContext struct { 51 HeaderContext 52 trunc bool 53 n types.NetworkResource 54 } 55 56 func (c *networkContext) MarshalJSON() ([]byte, error) { 57 return marshalJSON(c) 58 } 59 60 func (c *networkContext) ID() string { 61 c.AddHeader(networkIDHeader) 62 if c.trunc { 63 return stringid.TruncateID(c.n.ID) 64 } 65 return c.n.ID 66 } 67 68 func (c *networkContext) Name() string { 69 c.AddHeader(nameHeader) 70 return c.n.Name 71 } 72 73 func (c *networkContext) Driver() string { 74 c.AddHeader(driverHeader) 75 return c.n.Driver 76 } 77 78 func (c *networkContext) Scope() string { 79 c.AddHeader(scopeHeader) 80 return c.n.Scope 81 } 82 83 func (c *networkContext) IPv6() string { 84 c.AddHeader(ipv6Header) 85 return fmt.Sprintf("%v", c.n.EnableIPv6) 86 } 87 88 func (c *networkContext) Internal() string { 89 c.AddHeader(internalHeader) 90 return fmt.Sprintf("%v", c.n.Internal) 91 } 92 93 func (c *networkContext) Labels() string { 94 c.AddHeader(labelsHeader) 95 if c.n.Labels == nil { 96 return "" 97 } 98 99 var joinLabels []string 100 for k, v := range c.n.Labels { 101 joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v)) 102 } 103 return strings.Join(joinLabels, ",") 104 } 105 106 func (c *networkContext) Label(name string) string { 107 n := strings.Split(name, ".") 108 r := strings.NewReplacer("-", " ", "_", " ") 109 h := r.Replace(n[len(n)-1]) 110 111 c.AddHeader(h) 112 113 if c.n.Labels == nil { 114 return "" 115 } 116 return c.n.Labels[name] 117 }