containers.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import moby "github.com/docker/docker/api/types"
  15. // Containers is a set of moby Container
  16. type Containers []moby.Container
  17. // containerPredicate define a predicate we want container to satisfy for filtering operations
  18. type containerPredicate func(c moby.Container) bool
  19. func isService(services ...string) containerPredicate {
  20. return func(c moby.Container) bool {
  21. service := c.Labels[serviceLabel]
  22. return contains(services, service)
  23. }
  24. }
  25. func isNotService(services ...string) containerPredicate {
  26. return func(c moby.Container) bool {
  27. service := c.Labels[serviceLabel]
  28. return !contains(services, service)
  29. }
  30. }
  31. // filter return Containers with elements to match predicate
  32. func (containers Containers) filter(predicate containerPredicate) Containers {
  33. var filtered Containers
  34. for _, c := range containers {
  35. if predicate(c) {
  36. filtered = append(filtered, c)
  37. }
  38. }
  39. return filtered
  40. }
  41. // split return Containers with elements to match and those not to match predicate
  42. func (containers Containers) split(predicate containerPredicate) (Containers, Containers) {
  43. var right Containers
  44. var left Containers
  45. for _, c := range containers {
  46. if predicate(c) {
  47. right = append(right, c)
  48. } else {
  49. left = append(left, c)
  50. }
  51. }
  52. return right, left
  53. }
  54. func (containers Containers) names() []string {
  55. var names []string
  56. for _, c := range containers {
  57. names = append(names, getCanonicalContainerName(c))
  58. }
  59. return names
  60. }