Move compose v2 implementation under pkg/compose with dependencies

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
This commit is contained in:
Nicolas De Loof 2021-06-15 09:57:38 +02:00
parent e2ea24ceb7
commit 49e7f2d45d
93 changed files with 261 additions and 331 deletions

View File

@ -39,8 +39,8 @@ import (
"github.com/docker/compose-cli/api/client"
"github.com/docker/compose-cli/api/containers"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func createACIContainers(ctx context.Context, aciContext store.AciContext, groupDefinition containerinstance.ContainerGroup) error {

View File

@ -28,8 +28,8 @@ import (
"github.com/docker/compose-cli/aci/convert"
"github.com/docker/compose-cli/aci/login"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/utils/formatter"
)

View File

@ -29,7 +29,7 @@ import (
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils/prompt"
"github.com/docker/compose-cli/pkg/prompt"
)
// ContextParams options for creating ACI context

View File

@ -30,9 +30,9 @@ import (
"github.com/docker/compose-cli/aci/login"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/api/volumes"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
type aciVolumeService struct {

View File

@ -29,8 +29,8 @@ import (
"github.com/docker/compose-cli/api/client"
"github.com/docker/compose-cli/api/containers"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/cli/options/run"
"github.com/docker/compose-cli/pkg/progress"
)
// Command runs a container

View File

@ -23,10 +23,10 @@ import (
"github.com/docker/compose-cli/aci"
"github.com/docker/compose-cli/api/client"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/cli/formatter"
formatter2 "github.com/docker/compose-cli/cli/formatter"
format "github.com/docker/compose-cli/cli/formatter"
"github.com/docker/compose-cli/ecs"
"github.com/docker/compose-cli/pkg/progress"
"github.com/hashicorp/go-multierror"
"github.com/spf13/cobra"
@ -146,7 +146,7 @@ func inspectVolume() *cobra.Command {
if err != nil {
return err
}
outJSON, err := formatter2.ToStandardJSON(v)
outJSON, err := format.ToStandardJSON(v)
if err != nil {
return err
}

View File

@ -51,6 +51,7 @@ import (
compose2 "github.com/docker/compose-cli/cmd/compose"
"github.com/docker/compose-cli/local"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/compose"
// Backend registrations
_ "github.com/docker/compose-cli/aci"
@ -237,7 +238,7 @@ func main() {
if err = root.ExecuteContext(ctx); err != nil {
handleError(ctx, err, ctype, currentContext, cc, root)
}
metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
metrics.Track(ctype, os.Args[1:], compose.SuccessStatus)
}
func customizeCliForACI(command *cobra.Command, proxy *api.ServiceProxy) {
@ -271,7 +272,7 @@ func getBackend(ctype string, configDir string, opts cliopts.GlobalOpts) (backen
func handleError(ctx context.Context, err error, ctype string, currentContext string, cc *store.DockerContext, root *cobra.Command) {
// if user canceled request, simply exit without any error message
if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
metrics.Track(ctype, os.Args[1:], metrics.CanceledStatus)
metrics.Track(ctype, os.Args[1:], compose.CanceledStatus)
os.Exit(130)
}
if ctype == store.AwsContextType {
@ -293,20 +294,20 @@ $ docker context create %s <name>`, cc.Type(), store.EcsContextType), ctype)
func exit(ctx string, err error, ctype string) {
if exit, ok := err.(cli.StatusError); ok {
metrics.Track(ctype, os.Args[1:], metrics.SuccessStatus)
metrics.Track(ctype, os.Args[1:], compose.SuccessStatus)
os.Exit(exit.StatusCode)
}
var composeErr metrics.ComposeError
metricsStatus := metrics.FailureStatus
var composeErr compose.Error
metricsStatus := compose.FailureStatus
exitCode := 1
if errors.As(err, &composeErr) {
metricsStatus = composeErr.GetMetricsFailureCategory().MetricsStatus
exitCode = composeErr.GetMetricsFailureCategory().ExitCode
}
if strings.HasPrefix(err.Error(), "unknown shorthand flag:") || strings.HasPrefix(err.Error(), "unknown flag:") || strings.HasPrefix(err.Error(), "unknown docker command:") {
metricsStatus = metrics.CommandSyntaxFailure.MetricsStatus
exitCode = metrics.CommandSyntaxFailure.ExitCode
metricsStatus = compose.CommandSyntaxFailure.MetricsStatus
exitCode = compose.CommandSyntaxFailure.ExitCode
}
metrics.Track(ctype, os.Args[1:], metricsStatus)
@ -343,7 +344,7 @@ func checkIfUnknownCommandExistInDefaultContext(err error, currentContext string
if mobycli.IsDefaultContextCommand(dockerCommand) {
fmt.Fprintf(os.Stderr, "Command %q not available in current context (%s), you can use the \"default\" context to run this command\n", dockerCommand, currentContext)
metrics.Track(contextType, os.Args[1:], metrics.FailureStatus)
metrics.Track(contextType, os.Args[1:], compose.FailureStatus)
os.Exit(1)
}
}

View File

@ -21,7 +21,7 @@ import (
"os/exec"
"strings"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
var managementCommands = []string{"ecs", "scan"}

View File

@ -20,7 +20,7 @@ import (
"os"
"strings"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
// Track sends the tracking analytics to Docker Desktop

View File

@ -24,13 +24,14 @@ import (
"os/signal"
"regexp"
"github.com/spf13/cobra"
apicontext "github.com/docker/compose-cli/api/context"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/cli/metrics"
"github.com/docker/compose-cli/cli/mobycli/resolvepath"
"github.com/docker/compose-cli/utils"
"github.com/spf13/cobra"
"github.com/docker/compose-cli/pkg/compose"
"github.com/docker/compose-cli/pkg/utils"
)
var delegatedContextTypes = []string{store.DefaultContextType}
@ -68,10 +69,10 @@ func Exec(root *cobra.Command) {
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
exitCode := exiterr.ExitCode()
metrics.Track(store.DefaultContextType, os.Args[1:], metrics.ByExitCode(exitCode).MetricsStatus)
metrics.Track(store.DefaultContextType, os.Args[1:], compose.ByExitCode(exitCode).MetricsStatus)
os.Exit(exitCode)
}
metrics.Track(store.DefaultContextType, os.Args[1:], metrics.FailureStatus)
metrics.Track(store.DefaultContextType, os.Args[1:], compose.FailureStatus)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
@ -79,7 +80,7 @@ func Exec(root *cobra.Command) {
if command == "build" && !metrics.HasQuietFlag(os.Args[1:]) {
utils.DisplayScanSuggestMsg()
}
metrics.Track(store.DefaultContextType, os.Args[1:], metrics.SuccessStatus)
metrics.Track(store.DefaultContextType, os.Args[1:], compose.SuccessStatus)
os.Exit(0)
}

View File

@ -23,6 +23,7 @@ import (
"github.com/docker/compose-cli/cli/metrics"
"github.com/docker/compose-cli/cli/server/proxy"
"github.com/docker/compose-cli/pkg/compose"
)
var (
@ -60,16 +61,16 @@ func metricsServerInterceptor(client metrics.Client) grpc.UnaryServerInterceptor
data, err := handler(ctx, req)
status := metrics.SuccessStatus
status := compose.SuccessStatus
if err != nil {
status = metrics.FailureStatus
status = compose.FailureStatus
}
command := methodMapping[info.FullMethod]
if command != "" {
client.Send(metrics.Command{
Command: command,
Context: contextType,
Source: metrics.APISource,
Source: compose.APISource,
Status: status,
})
}

View File

@ -35,8 +35,8 @@ import (
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/cli/formatter"
"github.com/docker/compose-cli/cli/metrics"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/compose"
)
//Command defines a compose CLI command as a func with args
@ -58,11 +58,11 @@ func Adapt(fn Command) func(cmd *cobra.Command, args []string) error {
}()
}
err := fn(ctx, args)
var composeErr metrics.ComposeError
var composeErr compose.Error
if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) {
err = dockercli.StatusError{
StatusCode: 130,
Status: metrics.CanceledStatus,
Status: compose.CanceledStatus,
}
}
if errors.As(err, &composeErr) {
@ -155,12 +155,12 @@ func (o *projectOptions) toProjectName() (string, error) {
func (o *projectOptions) toProject(services []string, po ...cli.ProjectOptionsFn) (*types.Project, error) {
options, err := o.toProjectOptions(po...)
if err != nil {
return nil, metrics.WrapComposeError(err)
return nil, compose.WrapComposeError(err)
}
project, err := cli.ProjectFromOptions(options)
if err != nil {
return nil, metrics.WrapComposeError(err)
return nil, compose.WrapComposeError(err)
}
if len(services) > 0 {
@ -209,7 +209,7 @@ func RootCommand(contextType string, backend api.Service) *cobra.Command {
}
_ = cmd.Help()
return dockercli.StatusError{
StatusCode: metrics.CommandSyntaxFailure.ExitCode,
StatusCode: compose.CommandSyntaxFailure.ExitCode,
Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]),
}
},

View File

@ -33,7 +33,7 @@ import (
"github.com/spf13/cobra"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/compose"
)
type convertOptions struct {
@ -180,7 +180,7 @@ func runHash(opts convertOptions) error {
return err
}
for _, s := range project.Services {
hash, err := utils.ServiceHash(s)
hash, err := compose.ServiceHash(s)
if err != nil {
return err
}

View File

@ -24,14 +24,13 @@ import (
"sort"
"strings"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/go-units"
"github.com/spf13/cobra"
"github.com/docker/compose-cli/cli/formatter"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/go-units"
"github.com/docker/compose-cli/pkg/utils"
)
type imageOptions struct {

View File

@ -28,7 +28,7 @@ import (
"github.com/docker/compose-cli/cli/formatter"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
type psOptions struct {

View File

@ -25,7 +25,7 @@ import (
"github.com/spf13/cobra"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
type pullOptions struct {

View File

@ -29,8 +29,8 @@ import (
"github.com/spf13/cobra"
"github.com/docker/cli/cli"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
type runOptions struct {

View File

@ -24,10 +24,11 @@ import (
"strings"
"github.com/compose-spec/compose-go/types"
"github.com/spf13/cobra"
"github.com/docker/compose-cli/cli/formatter"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/spf13/cobra"
"github.com/docker/compose-cli/pkg/utils"
)
// composeOptions hold options common to `up` and `run` to run compose project

View File

@ -26,11 +26,10 @@ import (
"github.com/spf13/cobra"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/cli/metrics"
commands "github.com/docker/compose-cli/cmd/compose"
"github.com/docker/compose-cli/internal"
impl "github.com/docker/compose-cli/local/compose"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/compose"
)
func main() {
@ -42,7 +41,7 @@ func main() {
if err := plugin.PersistentPreRunE(cmd, args); err != nil {
return err
}
lazyInit.WithService(impl.NewComposeService(dockerCli.Client(), dockerCli.ConfigFile()))
lazyInit.WithService(compose.NewComposeService(dockerCli.Client(), dockerCli.ConfigFile()))
if originalPreRun != nil {
return originalPreRun(cmd, args)
}
@ -50,7 +49,7 @@ func main() {
}
cmd.SetFlagErrorFunc(func(c *cobra.Command, err error) error {
return dockercli.StatusError{
StatusCode: metrics.CommandSyntaxFailure.ExitCode,
StatusCode: compose.CommandSyntaxFailure.ExitCode,
Status: err.Error(),
}
})

View File

@ -24,9 +24,7 @@ import (
"sort"
"strings"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils/prompt"
"github.com/docker/compose-cli/pkg/prompt"
"github.com/AlecAivazis/survey/v2/terminal"
"github.com/aws/aws-sdk-go/aws"
@ -34,6 +32,8 @@ import (
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/pkg/api"
"github.com/pkg/errors"
"gopkg.in/ini.v1"
)

View File

@ -22,7 +22,7 @@ import (
"testing"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/utils/prompt"
"github.com/docker/compose-cli/pkg/prompt"
"github.com/golang/mock/gomock"
"gotest.tools/v3/assert"

View File

@ -21,8 +21,8 @@ import (
"github.com/pkg/errors"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (b *ecsAPIService) Down(ctx context.Context, projectName string, options api.DownOptions) error {

View File

@ -29,8 +29,8 @@ import (
"github.com/docker/compose-cli/api/resources"
"github.com/docker/compose-cli/api/secrets"
"github.com/docker/compose-cli/api/volumes"
local_compose "github.com/docker/compose-cli/local/compose"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/compose"
)
const backendType = store.EcsLocalSimulationContextType
@ -52,7 +52,7 @@ func service() (backend.Service, error) {
return &ecsLocalSimulation{
moby: apiClient,
compose: local_compose.NewComposeService(apiClient, cliconfig.LoadDefaultConfigFile(os.Stderr)),
compose: compose.NewComposeService(apiClient, cliconfig.LoadDefaultConfigFile(os.Stderr)),
}, nil
}

View File

@ -26,8 +26,8 @@ import (
"github.com/compose-spec/compose-go/types"
"github.com/sirupsen/logrus"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (b *ecsAPIService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {

View File

@ -23,10 +23,10 @@ import (
"strings"
"time"
"github.com/docker/compose-cli/pkg/progress"
"github.com/aws/aws-sdk-go/aws"
"github.com/iancoleman/strcase"
"github.com/docker/compose-cli/api/progress"
)
func (b *ecsAPIService) WaitStackCompletion(ctx context.Context, name string, operation int, ignored ...string) error { //nolint:gocyclo

View File

@ -28,7 +28,8 @@ import (
"time"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
"golang.org/x/sync/errgroup"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

View File

@ -23,7 +23,8 @@ import (
"time"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
corev1 "k8s.io/api/core/v1"
)

View File

@ -28,11 +28,12 @@ import (
apicontext "github.com/docker/compose-cli/api/context"
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/kube/client"
"github.com/docker/compose-cli/kube/helm"
"github.com/docker/compose-cli/kube/resources"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
utils2 "github.com/docker/compose-cli/pkg/utils"
"github.com/docker/compose-cli/utils"
)
@ -175,7 +176,7 @@ func (s *composeService) down(ctx context.Context, projectName string, options a
state = progress.Working
}
w.Event(progress.NewEvent(pod, state, message))
if !utils.StringContains(events, pod) {
if !utils2.StringContains(events, pod) {
events = append(events, pod)
}
},

View File

@ -26,7 +26,7 @@ import (
"github.com/docker/compose-cli/api/context/store"
"github.com/docker/compose-cli/kube/resources"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils/prompt"
"github.com/docker/compose-cli/pkg/prompt"
)
// ContextParams options for creating a Kubernetes context

View File

@ -30,8 +30,8 @@ import (
"github.com/docker/compose-cli/api/secrets"
"github.com/docker/compose-cli/api/volumes"
cliopts "github.com/docker/compose-cli/cli/options"
local_compose "github.com/docker/compose-cli/local/compose"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/compose"
)
type local struct {
@ -46,7 +46,7 @@ func NewService(apiClient client.APIClient) backend.Service {
return &local{
containerService: &containerService{apiClient},
volumeService: &volumeService{apiClient},
composeService: local_compose.NewComposeService(apiClient, file),
composeService: compose.NewComposeService(apiClient, file),
}
}

View File

@ -1,111 +0,0 @@
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package compose
import (
"fmt"
"github.com/docker/buildx/build"
"github.com/docker/compose-cli/cli/mobycli"
)
func (s *composeService) windowsBuild(opts map[string]build.Options, mode string) error {
for serviceName, options := range opts {
imageName := serviceName
dockerfile := options.Inputs.DockerfilePath
if options.Inputs.DockerfilePath == "-" { // image needs to be pulled
imageName := options.Tags[0]
err := shellOutMoby("pull", imageName)
if err != nil {
return err
}
} else {
cmd := &commandBuilder{
Path: options.Inputs.ContextPath,
}
cmd.addParams("--build-arg", options.BuildArgs)
cmd.addFlag("--pull", options.Pull)
cmd.addArg("--progress", mode)
cacheFrom := []string{}
for _, cacheImage := range options.CacheFrom {
cacheFrom = append(cacheFrom, cacheImage.Attrs["ref"])
}
cmd.addList("--cache-from", cacheFrom)
cmd.addArg("--file", dockerfile)
cmd.addParams("--label", options.Labels)
cmd.addArg("--network", options.NetworkMode)
cmd.addArg("--target", options.Target)
cmd.addList("--add-host", options.ExtraHosts)
cmd.addArg("--tag", imageName)
err := shellOutMoby(cmd.getArguments()...)
if err != nil {
return err
}
}
}
return nil
}
func shellOutMoby(args ...string) error {
childExit := make(chan bool)
err := mobycli.RunDocker(childExit, args...)
childExit <- true
return err
}
type commandBuilder struct {
Args []string
Path string
}
func (c *commandBuilder) addArg(name, value string) {
if value != "" {
c.Args = append(c.Args, name, value)
}
}
func (c *commandBuilder) addFlag(name string, flag bool) {
if flag {
c.Args = append(c.Args, name)
}
}
func (c *commandBuilder) addParams(name string, params map[string]string) {
if len(params) > 0 {
for k, v := range params {
c.Args = append(c.Args, name, fmt.Sprintf("%s=%s", k, v))
}
}
}
func (c *commandBuilder) addList(name string, values []string) {
if len(values) > 0 {
for _, v := range values {
c.Args = append(c.Args, name, v)
}
}
}
func (c *commandBuilder) getArguments() []string {
cmd := []string{"build"}
cmd = append(cmd, c.Args...)
cmd = append(cmd, c.Path)
return cmd
}

View File

@ -21,9 +21,7 @@ import (
"sort"
"strconv"
"strings"
"time"
compose "github.com/compose-spec/compose-go/types"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
@ -96,64 +94,6 @@ func ToPorts(ports []types.Port) []containers.Port {
return result
}
// ToMobyEnv convert into []string
func ToMobyEnv(environment compose.MappingWithEquals) []string {
var env []string
for k, v := range environment {
if v == nil {
env = append(env, k)
} else {
env = append(env, fmt.Sprintf("%s=%s", k, *v))
}
}
return env
}
// ToMobyHealthCheck convert into container.HealthConfig
func ToMobyHealthCheck(check *compose.HealthCheckConfig) *container.HealthConfig {
if check == nil {
return nil
}
var (
interval time.Duration
timeout time.Duration
period time.Duration
retries int
)
if check.Interval != nil {
interval = time.Duration(*check.Interval)
}
if check.Timeout != nil {
timeout = time.Duration(*check.Timeout)
}
if check.StartPeriod != nil {
period = time.Duration(*check.StartPeriod)
}
if check.Retries != nil {
retries = int(*check.Retries)
}
test := check.Test
if check.Disable {
test = []string{"NONE"}
}
return &container.HealthConfig{
Test: test,
Interval: interval,
Timeout: timeout,
StartPeriod: period,
Retries: retries,
}
}
// ToSeconds convert into seconds
func ToSeconds(d *compose.Duration) *int {
if d == nil {
return nil
}
s := int(time.Duration(*d).Seconds())
return &s
}
// FromPorts convert to nat.Port / nat.PortBinding
func FromPorts(ports []containers.Port) (map[nat.Port]struct{}, map[nat.Port][]nat.PortBinding, error) {
var (

View File

@ -22,14 +22,13 @@ import (
"io"
"strings"
convert "github.com/docker/compose-cli/local/moby"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/compose-spec/compose-go/types"
"github.com/docker/cli/cli/streams"
"github.com/docker/compose-cli/pkg/api"
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/stdcopy"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) attach(ctx context.Context, project *types.Project, listener api.ContainerEventListener, selectedServices []string) (Containers, error) {
@ -138,8 +137,8 @@ func (s *composeService) getContainerStreams(ctx context.Context, container stri
Logs: false,
})
if err == nil {
stdout = convert.ContainerStdout{HijackedResponse: cnx}
stdin = convert.ContainerStdin{HijackedResponse: cnx}
stdout = ContainerStdout{HijackedResponse: cnx}
stdin = ContainerStdin{HijackedResponse: cnx}
return stdin, stdout, nil
}

View File

@ -27,21 +27,20 @@ import (
"github.com/docker/buildx/driver"
_ "github.com/docker/buildx/driver/docker" // required to get default driver registered
"github.com/docker/buildx/util/buildflags"
"github.com/docker/buildx/util/progress"
xprogress "github.com/docker/buildx/util/progress"
moby "github.com/docker/docker/api/types"
bclient "github.com/moby/buildkit/client"
"github.com/moby/buildkit/session"
"github.com/moby/buildkit/session/auth/authprovider"
specs "github.com/opencontainers/image-spec/specs-go/v1"
composeprogress "github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/cli/metrics"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
return composeprogress.Run(ctx, func(ctx context.Context) error {
return progress.Run(ctx, func(ctx context.Context) error {
return s.build(ctx, project, options)
})
}
@ -108,9 +107,9 @@ func (s *composeService) ensureImagesExists(ctx context.Context, project *types.
return err
}
mode := progress.PrinterModeAuto
mode := xprogress.PrinterModeAuto
if quietPull {
mode = progress.PrinterModeQuiet
mode = xprogress.PrinterModeQuiet
}
opts, imagesToBuild, err := s.getBuildOptions(project, images)
if err != nil {
@ -193,7 +192,7 @@ func (s *composeService) doBuild(ctx context.Context, project *types.Project, op
// no support yet for Windows container builds in Buildkit
// https://docs.docker.com/develop/develop-images/build_enhancements/#limitations
err := s.windowsBuild(opts, mode)
return nil, metrics.WrapCategorisedComposeError(err, metrics.BuildFailure)
return nil, WrapCategorisedComposeError(err, BuildFailure)
}
if len(opts) == 0 {
return nil, nil
@ -216,7 +215,7 @@ func (s *composeService) doBuild(ctx context.Context, project *types.Project, op
// build and will lock
progressCtx, cancel := context.WithCancel(context.Background())
defer cancel()
w := progress.NewPrinter(progressCtx, os.Stdout, mode)
w := xprogress.NewPrinter(progressCtx, os.Stdout, mode)
// We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
response, err := build.Build(ctx, driverInfo, opts, nil, nil, w)
@ -225,10 +224,10 @@ func (s *composeService) doBuild(ctx context.Context, project *types.Project, op
err = errW
}
if err != nil {
return nil, metrics.WrapCategorisedComposeError(err, metrics.BuildFailure)
return nil, WrapCategorisedComposeError(err, BuildFailure)
}
cw := composeprogress.ContextWriter(ctx)
cw := progress.ContextWriter(ctx)
for _, c := range observedState {
for imageName := range opts {
if c.Image == imageName {

28
pkg/compose/build_win.go Normal file
View File

@ -0,0 +1,28 @@
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package compose
import (
"github.com/docker/buildx/build"
"github.com/docker/compose-cli/pkg/api"
)
func (s *composeService) windowsBuild(opts map[string]build.Options, mode string) error {
// FIXME copy/paste or reuse code from https://github.com/docker/cli/blob/master/cli/command/image/build.go
return api.ErrNotImplemented
}

View File

@ -14,7 +14,7 @@
limitations under the License.
*/
package moby
package compose
import (
"io"

View File

@ -24,7 +24,7 @@ import (
"github.com/docker/docker/api/types/filters"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
// Containers is a set of moby Container

View File

@ -31,10 +31,9 @@ import (
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/progress"
status "github.com/docker/compose-cli/local/moby"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/pkg/utils"
)
const (
@ -99,7 +98,7 @@ func (s *composeService) ensureService(ctx context.Context, project *types.Proje
return nil
}
expected, err := utils.ServiceHash(service)
expected, err := ServiceHash(service)
if err != nil {
return err
}
@ -118,11 +117,11 @@ func (s *composeService) ensureService(ctx context.Context, project *types.Proje
w := progress.ContextWriter(ctx)
switch container.State {
case status.ContainerRunning:
case ContainerRunning:
w.Event(progress.RunningEvent(name))
case status.ContainerCreated:
case status.ContainerRestarting:
case status.ContainerExited:
case ContainerCreated:
case ContainerRestarting:
case ContainerExited:
w.Event(progress.CreatedEvent(name))
default:
eg.Go(func() error {
@ -420,7 +419,7 @@ func (s *composeService) startService(ctx context.Context, project *types.Projec
eg, ctx := errgroup.WithContext(ctx)
for _, c := range containers {
container := c
if container.State == status.ContainerRunning {
if container.State == ContainerRunning {
continue
}
eg.Go(func() error {

83
pkg/compose/convert.go Normal file
View File

@ -0,0 +1,83 @@
/*
Copyright 2020 Docker Compose CLI authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package compose
import (
"fmt"
"time"
compose "github.com/compose-spec/compose-go/types"
"github.com/docker/docker/api/types/container"
)
// ToMobyEnv convert into []string
func ToMobyEnv(environment compose.MappingWithEquals) []string {
var env []string
for k, v := range environment {
if v == nil {
env = append(env, k)
} else {
env = append(env, fmt.Sprintf("%s=%s", k, *v))
}
}
return env
}
// ToMobyHealthCheck convert into container.HealthConfig
func ToMobyHealthCheck(check *compose.HealthCheckConfig) *container.HealthConfig {
if check == nil {
return nil
}
var (
interval time.Duration
timeout time.Duration
period time.Duration
retries int
)
if check.Interval != nil {
interval = time.Duration(*check.Interval)
}
if check.Timeout != nil {
timeout = time.Duration(*check.Timeout)
}
if check.StartPeriod != nil {
period = time.Duration(*check.StartPeriod)
}
if check.Retries != nil {
retries = int(*check.Retries)
}
test := check.Test
if check.Disable {
test = []string{"NONE"}
}
return &container.HealthConfig{
Test: test,
Interval: interval,
Timeout: timeout,
StartPeriod: period,
Retries: retries,
}
}
// ToSeconds convert into seconds
func ToSeconds(d *compose.Duration) *int {
if d == nil {
return nil
}
s := int(time.Duration(*d).Seconds())
return &s
}

View File

@ -38,11 +38,10 @@ import (
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/internal"
convert "github.com/docker/compose-cli/local/moby"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
@ -205,7 +204,7 @@ func getImageName(service types.ServiceConfig, projectName string) string {
func (s *composeService) getCreateOptions(ctx context.Context, p *types.Project, service types.ServiceConfig, number int, inherit *moby.Container,
autoRemove bool) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
hash, err := utils.ServiceHash(service)
hash, err := ServiceHash(service)
if err != nil {
return nil, nil, nil, err
}
@ -267,10 +266,10 @@ func (s *composeService) getCreateOptions(ctx context.Context, p *types.Project,
MacAddress: service.MacAddress,
Labels: labels,
StopSignal: service.StopSignal,
Env: convert.ToMobyEnv(service.Environment),
Healthcheck: convert.ToMobyHealthCheck(service.HealthCheck),
Env: ToMobyEnv(service.Environment),
Healthcheck: ToMobyHealthCheck(service.HealthCheck),
Volumes: volumeMounts,
StopTimeout: convert.ToSeconds(service.StopGracePeriod),
StopTimeout: ToSeconds(service.StopGracePeriod),
}
portBindings := buildContainerPortBindingOptions(service)

View File

@ -25,7 +25,7 @@ import (
"github.com/compose-spec/compose-go/types"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
// ServiceStatus indicates the status of a service

View File

@ -29,8 +29,8 @@ import (
"github.com/docker/docker/errdefs"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
type downOp func() error

View File

@ -20,8 +20,8 @@ import (
"context"
"testing"
"github.com/docker/compose-cli/local/mocks"
compose "github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/mocks"
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"

View File

@ -14,18 +14,18 @@
limitations under the License.
*/
package metrics
package compose
import (
"io/fs"
"github.com/pkg/errors"
composeerrdefs "github.com/compose-spec/compose-go/errdefs"
"github.com/compose-spec/compose-go/errdefs"
)
// ComposeError error to categorize failures and extract metrics info
type ComposeError struct {
// Error error to categorize failures and extract metrics info
type Error struct {
Err error
Category *FailureCategory
}
@ -35,7 +35,7 @@ func WrapComposeError(err error) error {
if err == nil {
return nil
}
return ComposeError{
return Error{
Err: err,
}
}
@ -45,19 +45,19 @@ func WrapCategorisedComposeError(err error, failure FailureCategory) error {
if err == nil {
return nil
}
return ComposeError{
return Error{
Err: err,
Category: &failure,
}
}
// Unwrap get underlying error
func (e ComposeError) Unwrap() error { return e.Err }
func (e Error) Unwrap() error { return e.Err }
func (e ComposeError) Error() string { return e.Err.Error() }
func (e Error) Error() string { return e.Err.Error() }
// GetMetricsFailureCategory get metrics status and error code corresponding to this error
func (e ComposeError) GetMetricsFailureCategory() FailureCategory {
func (e Error) GetMetricsFailureCategory() FailureCategory {
if e.Category != nil {
return *e.Category
}
@ -65,7 +65,7 @@ func (e ComposeError) GetMetricsFailureCategory() FailureCategory {
if errors.As(e.Err, &pathError) {
return FileNotFoundFailure
}
if composeerrdefs.IsNotFoundError(e.Err) {
if errdefs.IsNotFoundError(e.Err) {
return FileNotFoundFailure
}
return ComposeParseFailure

View File

@ -22,10 +22,10 @@ import (
"time"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Events(ctx context.Context, project string, options api.EventsOptions) error {

View File

@ -14,7 +14,7 @@
limitations under the License.
*/
package utils
package compose
import (
"encoding/json"

View File

@ -28,7 +28,7 @@ import (
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Images(ctx context.Context, projectName string, options api.ImagesOptions) ([]api.ImageSummary, error) {

View File

@ -23,8 +23,8 @@ import (
moby "github.com/docker/docker/api/types"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (s *composeService) Kill(ctx context.Context, project *types.Project, options api.KillOptions) error {

View File

@ -21,15 +21,14 @@ import (
"path/filepath"
"testing"
"github.com/compose-spec/compose-go/types"
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/golang/mock/gomock"
"gotest.tools/v3/assert"
"github.com/compose-spec/compose-go/types"
moby "github.com/docker/docker/api/types"
"github.com/docker/compose-cli/local/mocks"
compose "github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/mocks"
)
const testProject = "testProject"

View File

@ -21,11 +21,11 @@ import (
"io"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/stdcopy"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Logs(ctx context.Context, projectName string, consumer api.LogConsumer, options api.LogOptions) error {

View File

@ -14,7 +14,7 @@
limitations under the License.
*/
package metrics
package compose
// FailureCategory sruct regrouping metrics failure status and specific exit code
type FailureCategory struct {
@ -76,5 +76,4 @@ func ByExitCode(exitCode int) FailureCategory {
default:
return FailureCategory{MetricsStatus: FailureStatus, ExitCode: exitCode}
}
}

View File

@ -22,8 +22,8 @@ import (
moby "github.com/docker/docker/api/types"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (s *composeService) Pause(ctx context.Context, project string, options api.PauseOptions) error {

View File

@ -26,8 +26,8 @@ import (
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/compose-cli/local/mocks"
compose "github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/mocks"
)
func TestPs(t *testing.T) {

View File

@ -32,9 +32,8 @@ import (
"github.com/docker/docker/registry"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/cli/metrics"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (s *composeService) Pull(ctx context.Context, project *types.Project, opts api.PullOptions) error {
@ -125,7 +124,7 @@ func (s *composeService) pullServiceImage(ctx context.Context, service types.Ser
Status: progress.Error,
Text: "Error",
})
return metrics.WrapCategorisedComposeError(err, metrics.PullFailure)
return WrapCategorisedComposeError(err, PullFailure)
}
dec := json.NewDecoder(stream)
@ -135,10 +134,10 @@ func (s *composeService) pullServiceImage(ctx context.Context, service types.Ser
if err == io.EOF {
break
}
return metrics.WrapCategorisedComposeError(err, metrics.PullFailure)
return WrapCategorisedComposeError(err, PullFailure)
}
if jm.Error != nil {
return metrics.WrapCategorisedComposeError(errors.New(jm.Error.Message), metrics.PullFailure)
return WrapCategorisedComposeError(errors.New(jm.Error.Message), PullFailure)
}
if !quietPull {
toPullProgressEvent(service.Name, jm, w)

View File

@ -26,16 +26,14 @@ import (
"github.com/compose-spec/compose-go/types"
"github.com/distribution/distribution/v3/reference"
"github.com/docker/buildx/driver"
cliconfig "github.com/docker/cli/cli/config"
moby "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/registry"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/config"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (s *composeService) Push(ctx context.Context, project *types.Project, options api.PushOptions) error {
@ -45,10 +43,6 @@ func (s *composeService) Push(ctx context.Context, project *types.Project, optio
}
func (s *composeService) push(ctx context.Context, project *types.Project, options api.PushOptions) error {
configFile, err := cliconfig.Load(config.Dir())
if err != nil {
return err
}
eg, ctx := errgroup.WithContext(ctx)
info, err := s.apiClient.Info(ctx)
@ -71,7 +65,7 @@ func (s *composeService) push(ctx context.Context, project *types.Project, optio
}
service := service
eg.Go(func() error {
err := s.pushServiceImage(ctx, service, info, configFile, w)
err := s.pushServiceImage(ctx, service, info, s.configFile, w)
if err != nil {
if !options.IgnoreFailures {
return err

View File

@ -21,14 +21,13 @@ import (
"fmt"
"strings"
"github.com/docker/compose-cli/api/progress"
status "github.com/docker/compose-cli/local/moby"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils/prompt"
"github.com/compose-spec/compose-go/types"
"github.com/docker/compose-cli/pkg/api"
moby "github.com/docker/docker/api/types"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/pkg/prompt"
)
func (s *composeService) Remove(ctx context.Context, project *types.Project, options api.RemoveOptions) error {
@ -43,7 +42,7 @@ func (s *composeService) Remove(ctx context.Context, project *types.Project, opt
}
stoppedContainers := containers.filter(func(c moby.Container) bool {
return c.State != status.ContainerRunning
return c.State != ContainerRunning
})
var names []string

View File

@ -19,11 +19,11 @@ package compose
import (
"context"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/utils"
"github.com/compose-spec/compose-go/types"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
"github.com/docker/compose-cli/pkg/utils"
)
func (s *composeService) Restart(ctx context.Context, project *types.Project, options api.RestartOptions) error {

View File

@ -24,8 +24,8 @@ import (
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
)
func (s *composeService) Start(ctx context.Context, project *types.Project, options api.StartOptions) error {

View File

@ -19,8 +19,8 @@ package compose
import (
"context"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
"github.com/compose-spec/compose-go/types"
)

View File

@ -21,12 +21,11 @@ import (
"testing"
"time"
moby "github.com/docker/docker/api/types"
"github.com/docker/compose-cli/local/mocks"
compose "github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/mocks"
"github.com/compose-spec/compose-go/types"
moby "github.com/docker/docker/api/types"
"github.com/golang/mock/gomock"
"gotest.tools/v3/assert"
)

View File

@ -23,8 +23,8 @@ import (
"os/signal"
"syscall"
"github.com/docker/compose-cli/api/progress"
"github.com/docker/compose-cli/pkg/api"
"github.com/docker/compose-cli/pkg/progress"
"github.com/compose-spec/compose-go/types"
"github.com/docker/cli/cli"

View File

@ -25,7 +25,7 @@ import (
"sync"
"time"
"github.com/docker/compose-cli/utils"
"github.com/docker/compose-cli/pkg/utils"
"github.com/buger/goterm"
"github.com/morikuni/aec"

View File

@ -20,7 +20,7 @@ import (
"github.com/AlecAivazis/survey/v2"
)
//go:generate mockgen -destination=./prompt_mock.go -self_package "github.com/docker/compose-cli/prompt" -package=prompt . UI
//go:generate mockgen -destination=./prompt_mock.go -self_package "github.com/docker/compose-cli/pkg/prompt" -package=prompt . UI
// UI - prompt user input
type UI interface {

View File

@ -1,5 +1,5 @@
// Code generated by MockGen. DO NOT EDIT.
// Container: github.com/docker/compose-cli/prompt (interfaces: UI)
// Container: github.com/docker/compose-cli/pkg/prompt (interfaces: UI)
// Package prompt is a generated GoMock package.
package prompt