compose.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "strings"
  19. "github.com/docker/compose-cli/api/compose"
  20. "github.com/compose-spec/compose-go/types"
  21. moby "github.com/docker/docker/api/types"
  22. "github.com/docker/docker/client"
  23. "github.com/sanathkr/go-yaml"
  24. errdefs2 "github.com/docker/compose-cli/api/errdefs"
  25. )
  26. // NewComposeService create a local implementation of the compose.Service API
  27. func NewComposeService(apiClient client.APIClient) compose.Service {
  28. return &composeService{apiClient: apiClient}
  29. }
  30. type composeService struct {
  31. apiClient client.APIClient
  32. }
  33. func (s *composeService) Up(ctx context.Context, project *types.Project, options compose.UpOptions) error {
  34. return errdefs2.ErrNotImplemented
  35. }
  36. func getCanonicalContainerName(c moby.Container) string {
  37. // Names return container canonical name /foo + link aliases /linked_by/foo
  38. for _, name := range c.Names {
  39. if strings.LastIndex(name, "/") == 0 {
  40. return name[1:]
  41. }
  42. }
  43. return c.Names[0][1:]
  44. }
  45. func getContainerNameWithoutProject(c moby.Container) string {
  46. name := getCanonicalContainerName(c)
  47. project := c.Labels[projectLabel]
  48. prefix := fmt.Sprintf("%s_%s_", project, c.Labels[serviceLabel])
  49. if strings.HasPrefix(name, prefix) {
  50. return name[len(project)+1:]
  51. }
  52. return name
  53. }
  54. func (s *composeService) Convert(ctx context.Context, project *types.Project, options compose.ConvertOptions) ([]byte, error) {
  55. switch options.Format {
  56. case "json":
  57. return json.MarshalIndent(project, "", " ")
  58. case "yaml":
  59. return yaml.Marshal(project)
  60. default:
  61. return nil, fmt.Errorf("unsupported format %q", options)
  62. }
  63. }