github.com/ijc/docker-app@v0.6.1-0.20181012090447-c7ca8bc483fb/internal/inspect/ports.go (about) 1 package inspect 2 3 import ( 4 "fmt" 5 "sort" 6 "strings" 7 8 composetypes "github.com/docker/cli/cli/compose/types" 9 ) 10 11 type portRange struct { 12 start uint32 13 end *uint32 14 } 15 16 func newPort(start uint32) *portRange { 17 return &portRange{start: start} 18 } 19 20 func (p *portRange) add(end uint32) bool { 21 if p.end == nil { 22 if p.start+1 == end { 23 p.end = &end 24 return true 25 } 26 return false 27 } 28 if *p.end+1 == end { 29 p.end = &end 30 return true 31 32 } 33 return false 34 } 35 36 func (p portRange) String() string { 37 res := fmt.Sprintf("%d", p.start) 38 if p.end != nil { 39 res += fmt.Sprintf("-%d", *p.end) 40 } 41 return res 42 } 43 44 // getPorts identifies all the published port ranges, merges them 45 // if they are consecutive, and return a string with all the published 46 // ports. 47 func getPorts(ports []composetypes.ServicePortConfig) string { 48 var ( 49 portRanges []*portRange 50 lastPortRange *portRange 51 ) 52 sort.Slice(ports, func(i int, j int) bool { return ports[i].Published < ports[j].Published }) 53 for _, port := range ports { 54 if port.Published > 0 { 55 if lastPortRange == nil { 56 lastPortRange = newPort(port.Published) 57 } else if !lastPortRange.add(port.Published) { 58 portRanges = append(portRanges, lastPortRange) 59 lastPortRange = newPort(port.Published) 60 } 61 } 62 } 63 if lastPortRange != nil { 64 portRanges = append(portRanges, lastPortRange) 65 } 66 output := make([]string, len(portRanges)) 67 for i, p := range portRanges { 68 output[i] = p.String() 69 } 70 return strings.Join(output, ",") 71 }