repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/pretty.go
cmd/formatter/pretty.go
/* 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 formatter import ( "fmt" "io" "strings" "text/tabwriter" ) // PrintPrettySection prints a tabbed section on the writer parameter func PrintPrettySection(out io.Writer, printer func(writer io.Writer), headers ...string) error { w := tabwriter.NewWriter(out, 20, 1, 3, ' ', 0) _, _ = fmt.Fprintln(w, strings.Join(headers, "\t")) printer(w) return w.Flush() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/consts.go
cmd/formatter/consts.go
/* 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 formatter const ( // JSON Print in JSON format JSON = "json" // TemplateLegacyJSON the legacy json formatting value using go template TemplateLegacyJSON = "{{json.}}" // PRETTY is the constant for default formats on list commands // // Deprecated: use TABLE PRETTY = "pretty" // TABLE Print output in table format with column headers (default) TABLE = "table" )
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/container.go
cmd/formatter/container.go
/* 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 formatter import ( "fmt" "strconv" "strings" "time" "github.com/docker/cli/cli/command/formatter" "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/stringid" "github.com/docker/go-units" "github.com/docker/compose/v5/pkg/api" ) const ( defaultContainerTableFormat = "table {{.Name}}\t{{.Image}}\t{{.Command}}\t{{.Service}}\t{{.RunningFor}}\t{{.Status}}\t{{.Ports}}" nameHeader = "NAME" projectHeader = "PROJECT" serviceHeader = "SERVICE" commandHeader = "COMMAND" runningForHeader = "CREATED" mountsHeader = "MOUNTS" localVolumes = "LOCAL VOLUMES" networksHeader = "NETWORKS" ) // NewContainerFormat returns a Format for rendering using a Context func NewContainerFormat(source string, quiet bool, size bool) formatter.Format { switch source { case formatter.TableFormatKey, "": // table formatting is the default if none is set. if quiet { return formatter.DefaultQuietFormat } format := defaultContainerTableFormat if size { format += `\t{{.Size}}` } return formatter.Format(format) case formatter.RawFormatKey: if quiet { return `container_id: {{.ID}}` } format := `container_id: {{.ID}} image: {{.Image}} command: {{.Command}} created_at: {{.CreatedAt}} state: {{- pad .State 1 0}} status: {{- pad .Status 1 0}} names: {{.Names}} labels: {{- pad .Labels 1 0}} ports: {{- pad .Ports 1 0}} ` if size { format += `size: {{.Size}}\n` } return formatter.Format(format) default: // custom format if quiet { return formatter.DefaultQuietFormat } return formatter.Format(source) } } // ContainerWrite renders the context for a list of containers func ContainerWrite(ctx formatter.Context, containers []api.ContainerSummary) error { render := func(format func(subContext formatter.SubContext) error) error { for _, container := range containers { err := format(&ContainerContext{trunc: ctx.Trunc, c: container}) if err != nil { return err } } return nil } return ctx.Write(NewContainerContext(), render) } // ContainerContext is a struct used for rendering a list of containers in a Go template. type ContainerContext struct { formatter.HeaderContext trunc bool c api.ContainerSummary // FieldsUsed is used in the pre-processing step to detect which fields are // used in the template. It's currently only used to detect use of the .Size // field which (if used) automatically sets the '--size' option when making // the API call. FieldsUsed map[string]any } // NewContainerContext creates a new context for rendering containers func NewContainerContext() *ContainerContext { containerCtx := ContainerContext{} containerCtx.Header = formatter.SubHeaderContext{ "ID": formatter.ContainerIDHeader, "Name": nameHeader, "Project": projectHeader, "Service": serviceHeader, "Image": formatter.ImageHeader, "Command": commandHeader, "CreatedAt": formatter.CreatedAtHeader, "RunningFor": runningForHeader, "Ports": formatter.PortsHeader, "State": formatter.StateHeader, "Status": formatter.StatusHeader, "Size": formatter.SizeHeader, "Labels": formatter.LabelsHeader, } return &containerCtx } // MarshalJSON makes ContainerContext implement json.Marshaler func (c *ContainerContext) MarshalJSON() ([]byte, error) { return formatter.MarshalJSON(c) } // ID returns the container's ID as a string. Depending on the `--no-trunc` // option being set, the full or truncated ID is returned. func (c *ContainerContext) ID() string { if c.trunc { return stringid.TruncateID(c.c.ID) } return c.c.ID } func (c *ContainerContext) Name() string { return c.c.Name } // Names returns a comma-separated string of the container's names, with their // slash (/) prefix stripped. Additional names for the container (related to the // legacy `--link` feature) are omitted. func (c *ContainerContext) Names() string { names := formatter.StripNamePrefix(c.c.Names) if c.trunc { for _, name := range names { if len(strings.Split(name, "/")) == 1 { names = []string{name} break } } } return strings.Join(names, ",") } func (c *ContainerContext) Service() string { return c.c.Service } func (c *ContainerContext) Project() string { return c.c.Project } func (c *ContainerContext) Image() string { return c.c.Image } func (c *ContainerContext) Command() string { command := c.c.Command if c.trunc { command = formatter.Ellipsis(command, 20) } return strconv.Quote(command) } func (c *ContainerContext) CreatedAt() string { return time.Unix(c.c.Created, 0).String() } func (c *ContainerContext) RunningFor() string { createdAt := time.Unix(c.c.Created, 0) return units.HumanDuration(time.Now().UTC().Sub(createdAt)) + " ago" } func (c *ContainerContext) ExitCode() int { return c.c.ExitCode } func (c *ContainerContext) State() string { return c.c.State } func (c *ContainerContext) Status() string { return c.c.Status } func (c *ContainerContext) Health() string { return c.c.Health } func (c *ContainerContext) Publishers() api.PortPublishers { return c.c.Publishers } func (c *ContainerContext) Ports() string { var ports []container.Port for _, publisher := range c.c.Publishers { ports = append(ports, container.Port{ IP: publisher.URL, PrivatePort: uint16(publisher.TargetPort), PublicPort: uint16(publisher.PublishedPort), Type: publisher.Protocol, }) } return formatter.DisplayablePorts(ports) } // Labels returns a comma-separated string of labels present on the container. func (c *ContainerContext) Labels() string { if c.c.Labels == nil { return "" } var joinLabels []string for k, v := range c.c.Labels { joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v)) } return strings.Join(joinLabels, ",") } // Label returns the value of the label with the given name or an empty string // if the given label does not exist. func (c *ContainerContext) Label(name string) string { if c.c.Labels == nil { return "" } return c.c.Labels[name] } // Mounts returns a comma-separated string of mount names present on the container. // If the trunc option is set, names can be truncated (ellipsized). func (c *ContainerContext) Mounts() string { var mounts []string for _, name := range c.c.Mounts { if c.trunc { name = formatter.Ellipsis(name, 15) } mounts = append(mounts, name) } return strings.Join(mounts, ",") } // LocalVolumes returns the number of volumes using the "local" volume driver. func (c *ContainerContext) LocalVolumes() string { return fmt.Sprintf("%d", c.c.LocalVolumes) } // Networks returns a comma-separated string of networks that the container is // attached to. func (c *ContainerContext) Networks() string { return strings.Join(c.c.Networks, ",") } // Size returns the container's size and virtual size (e.g. "2B (virtual 21.5MB)") func (c *ContainerContext) Size() string { if c.FieldsUsed == nil { c.FieldsUsed = map[string]any{} } c.FieldsUsed["Size"] = struct{}{} srw := units.HumanSizeWithPrecision(float64(c.c.SizeRw), 3) sv := units.HumanSizeWithPrecision(float64(c.c.SizeRootFs), 3) sf := srw if c.c.SizeRootFs > 0 { sf = fmt.Sprintf("%s (virtual %s)", srw, sv) } return sf }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/shortcut_windows.go
cmd/formatter/shortcut_windows.go
//go:build windows /* Copyright 2024 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 formatter // handleCtrlZ is a no-op on Windows as SIGSTOP is not supported func handleCtrlZ() { // Windows doesn't support SIGSTOP/SIGCONT signals // Ctrl+Z behavior is handled differently by the Windows terminal }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/formatter.go
cmd/formatter/formatter.go
/* 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 formatter import ( "fmt" "io" "reflect" "strings" "github.com/docker/compose/v5/pkg/api" ) // Print prints formatted lists in different formats func Print(toJSON any, format string, outWriter io.Writer, writerFn func(w io.Writer), headers ...string) error { switch strings.ToLower(format) { case TABLE, PRETTY, "": return PrintPrettySection(outWriter, writerFn, headers...) case TemplateLegacyJSON: switch reflect.TypeOf(toJSON).Kind() { case reflect.Slice: s := reflect.ValueOf(toJSON) for i := 0; i < s.Len(); i++ { obj := s.Index(i).Interface() outJSON, err := ToJSON(obj, "", "") if err != nil { return err } _, _ = fmt.Fprint(outWriter, outJSON) } default: outJSON, err := ToStandardJSON(toJSON) if err != nil { return err } _, _ = fmt.Fprintln(outWriter, outJSON) } case JSON: switch reflect.TypeOf(toJSON).Kind() { case reflect.Slice: outJSON, err := ToJSON(toJSON, "", "") if err != nil { return err } _, _ = fmt.Fprint(outWriter, outJSON) default: outJSON, err := ToStandardJSON(toJSON) if err != nil { return err } _, _ = fmt.Fprintln(outWriter, outJSON) } default: return fmt.Errorf("format value %q could not be parsed: %w", format, api.ErrParsingFailed) } return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/shortcut_unix.go
cmd/formatter/shortcut_unix.go
//go:build !windows /* Copyright 2024 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 formatter import "syscall" func handleCtrlZ() { _ = syscall.Kill(0, syscall.SIGSTOP) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/logs.go
cmd/formatter/logs.go
/* 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 formatter import ( "context" "fmt" "io" "strconv" "strings" "sync" "time" "github.com/buger/goterm" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/compose/v5/pkg/api" ) // LogConsumer consume logs from services and format them type logConsumer struct { ctx context.Context presenters sync.Map // map[string]*presenter width int stdout io.Writer stderr io.Writer color bool prefix bool timestamp bool } // NewLogConsumer creates a new LogConsumer func NewLogConsumer(ctx context.Context, stdout, stderr io.Writer, color, prefix, timestamp bool) api.LogConsumer { return &logConsumer{ ctx: ctx, presenters: sync.Map{}, width: 0, stdout: stdout, stderr: stderr, color: color, prefix: prefix, timestamp: timestamp, } } func (l *logConsumer) register(name string) *presenter { var p *presenter root, _, found := strings.Cut(name, " ") if found { parent := l.getPresenter(root) p = &presenter{ colors: parent.colors, name: name, prefix: parent.prefix, } } else { cf := monochrome if l.color { switch name { case "": cf = monochrome case api.WatchLogger: cf = makeColorFunc("92") default: cf = nextColor() } } p = &presenter{ colors: cf, name: name, } } l.presenters.Store(name, p) l.computeWidth() if l.prefix { l.presenters.Range(func(key, value any) bool { p := value.(*presenter) p.setPrefix(l.width) return true }) } return p } func (l *logConsumer) getPresenter(container string) *presenter { p, ok := l.presenters.Load(container) if !ok { // should have been registered, but ¯\_(ツ)_/¯ return l.register(container) } return p.(*presenter) } // Log formats a log message as received from name/container func (l *logConsumer) Log(container, message string) { l.write(l.stdout, container, message) } // Err formats a log message as received from name/container func (l *logConsumer) Err(container, message string) { l.write(l.stderr, container, message) } func (l *logConsumer) write(w io.Writer, container, message string) { if l.ctx.Err() != nil { return } p := l.getPresenter(container) timestamp := time.Now().Format(jsonmessage.RFC3339NanoFixed) for line := range strings.SplitSeq(message, "\n") { if l.timestamp { _, _ = fmt.Fprintf(w, "%s%s %s\n", p.prefix, timestamp, line) } else { _, _ = fmt.Fprintf(w, "%s%s\n", p.prefix, line) } } } func (l *logConsumer) Status(container, msg string) { p := l.getPresenter(container) s := p.colors(fmt.Sprintf("%s%s %s\n", goterm.RESET_LINE, container, msg)) l.stdout.Write([]byte(s)) //nolint:errcheck } func (l *logConsumer) computeWidth() { width := 0 l.presenters.Range(func(key, value any) bool { p := value.(*presenter) if len(p.name) > width { width = len(p.name) } return true }) l.width = width + 1 } type presenter struct { colors colorFunc name string prefix string } func (p *presenter) setPrefix(width int) { if p.name == api.WatchLogger { p.prefix = p.colors(strings.Repeat(" ", width) + " ⦿ ") return } p.prefix = p.colors(fmt.Sprintf("%-"+strconv.Itoa(width)+"s | ", p.name)) } type logDecorator struct { decorated api.LogConsumer Before func() After func() } func (l logDecorator) Log(containerName, message string) { l.Before() l.decorated.Log(containerName, message) l.After() } func (l logDecorator) Err(containerName, message string) { l.Before() l.decorated.Err(containerName, message) l.After() } func (l logDecorator) Status(container, msg string) { l.Before() l.decorated.Status(container, msg) l.After() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/colors.go
cmd/formatter/colors.go
/* 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 formatter import ( "fmt" "strconv" "strings" "sync" "github.com/docker/cli/cli/command" ) var names = []string{ "grey", "red", "green", "yellow", "blue", "magenta", "cyan", "white", } const ( BOLD = "1" FAINT = "2" ITALIC = "3" UNDERLINE = "4" ) const ( RESET = "0" CYAN = "36" ) const ( // Never use ANSI codes Never = "never" // Always use ANSI codes Always = "always" // Auto detect terminal is a tty and can use ANSI codes Auto = "auto" ) // ansiColorOffset is the offset for basic foreground colors in ANSI escape codes. const ansiColorOffset = 30 // SetANSIMode configure formatter for colored output on ANSI-compliant console func SetANSIMode(streams command.Streams, ansi string) { if !useAnsi(streams, ansi) { nextColor = func() colorFunc { return monochrome } disableAnsi = true } } func useAnsi(streams command.Streams, ansi string) bool { switch ansi { case Always: return true case Auto: return streams.Out().IsTerminal() } return false } // colorFunc use ANSI codes to render colored text on console type colorFunc func(s string) string var monochrome = func(s string) string { return s } func ansiColor(code, s string, formatOpts ...string) string { return fmt.Sprintf("%s%s%s", ansiColorCode(code, formatOpts...), s, ansiColorCode("0")) } // Everything about ansiColorCode color https://hyperskill.org/learn/step/18193 func ansiColorCode(code string, formatOpts ...string) string { var sb strings.Builder sb.WriteString("\033[") for _, c := range formatOpts { sb.WriteString(c) sb.WriteString(";") } sb.WriteString(code) sb.WriteString("m") return sb.String() } func makeColorFunc(code string) colorFunc { return func(s string) string { return ansiColor(code, s) } } var ( nextColor = rainbowColor rainbow []colorFunc currentIndex = 0 mutex sync.Mutex ) func rainbowColor() colorFunc { mutex.Lock() defer mutex.Unlock() result := rainbow[currentIndex] currentIndex = (currentIndex + 1) % len(rainbow) return result } func init() { colors := map[string]colorFunc{} for i, name := range names { colors[name] = makeColorFunc(strconv.Itoa(ansiColorOffset + i)) colors["intense_"+name] = makeColorFunc(strconv.Itoa(ansiColorOffset+i) + ";1") } rainbow = []colorFunc{ colors["cyan"], colors["yellow"], colors["green"], colors["magenta"], colors["blue"], colors["intense_cyan"], colors["intense_yellow"], colors["intense_green"], colors["intense_magenta"], colors["intense_blue"], } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/shortcut.go
cmd/formatter/shortcut.go
/* Copyright 2024 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 formatter import ( "context" "errors" "fmt" "math" "os" "strings" "syscall" "time" "github.com/buger/goterm" "github.com/compose-spec/compose-go/v2/types" "github.com/eiannone/keyboard" "github.com/skratchdot/open-golang/open" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" ) const DISPLAY_ERROR_TIME = 10 type KeyboardError struct { err error timeStart time.Time } func (ke *KeyboardError) shouldDisplay() bool { return ke.err != nil && int(time.Since(ke.timeStart).Seconds()) < DISPLAY_ERROR_TIME } func (ke *KeyboardError) printError(height int, info string) { if ke.shouldDisplay() { errMessage := ke.err.Error() moveCursor(height-1-extraLines(info)-extraLines(errMessage), 0) clearLine() fmt.Print(errMessage) } } func (ke *KeyboardError) addError(prefix string, err error) { ke.timeStart = time.Now() prefix = ansiColor(CYAN, fmt.Sprintf("%s →", prefix), BOLD) errorString := fmt.Sprintf("%s %s", prefix, err.Error()) ke.err = errors.New(errorString) } func (ke *KeyboardError) error() string { return ke.err.Error() } type KeyboardWatch struct { Watching bool Watcher Feature } // Feature is an compose feature that can be started/stopped by a menu command type Feature interface { Start(context.Context) error Stop() error } type KEYBOARD_LOG_LEVEL int const ( NONE KEYBOARD_LOG_LEVEL = 0 INFO KEYBOARD_LOG_LEVEL = 1 DEBUG KEYBOARD_LOG_LEVEL = 2 ) type LogKeyboard struct { kError KeyboardError Watch *KeyboardWatch Detach func() IsDockerDesktopActive bool logLevel KEYBOARD_LOG_LEVEL signalChannel chan<- os.Signal } func NewKeyboardManager(isDockerDesktopActive bool, sc chan<- os.Signal) *LogKeyboard { return &LogKeyboard{ IsDockerDesktopActive: isDockerDesktopActive, logLevel: INFO, signalChannel: sc, } } func (lk *LogKeyboard) Decorate(l api.LogConsumer) api.LogConsumer { return logDecorator{ decorated: l, Before: lk.clearNavigationMenu, After: lk.PrintKeyboardInfo, } } func (lk *LogKeyboard) PrintKeyboardInfo() { if lk.logLevel == INFO { lk.printNavigationMenu() } } // Creates space to print error and menu string func (lk *LogKeyboard) createBuffer(lines int) { if lk.kError.shouldDisplay() { extraLines := extraLines(lk.kError.error()) + 1 lines += extraLines } // get the string infoMessage := lk.navigationMenu() // calculate how many lines we need to display the menu info // might be needed a line break extraLines := extraLines(infoMessage) + 1 lines += extraLines if lines > 0 { allocateSpace(lines) moveCursorUp(lines) } } func (lk *LogKeyboard) printNavigationMenu() { offset := 1 lk.clearNavigationMenu() lk.createBuffer(offset) if lk.logLevel == INFO { height := goterm.Height() menu := lk.navigationMenu() carriageReturn() saveCursor() lk.kError.printError(height, menu) moveCursor(height-extraLines(menu), 0) clearLine() fmt.Print(menu) carriageReturn() restoreCursor() } } func (lk *LogKeyboard) navigationMenu() string { var items []string if lk.IsDockerDesktopActive { items = append(items, shortcutKeyColor("v")+navColor(" View in Docker Desktop")) } if lk.IsDockerDesktopActive { items = append(items, shortcutKeyColor("o")+navColor(" View Config")) } isEnabled := " Enable" if lk.Watch != nil && lk.Watch.Watching { isEnabled = " Disable" } items = append(items, shortcutKeyColor("w")+navColor(isEnabled+" Watch")) items = append(items, shortcutKeyColor("d")+navColor(" Detach")) return strings.Join(items, " ") } func (lk *LogKeyboard) clearNavigationMenu() { height := goterm.Height() carriageReturn() saveCursor() // clearLine() for i := 0; i < height; i++ { moveCursorDown(1) clearLine() } restoreCursor() } func (lk *LogKeyboard) openDockerDesktop(ctx context.Context, project *types.Project) { if !lk.IsDockerDesktopActive { return } go func() { _ = tracing.EventWrapFuncForErrGroup(ctx, "menu/gui", tracing.SpanOptions{}, func(ctx context.Context) error { link := fmt.Sprintf("docker-desktop://dashboard/apps/%s", project.Name) err := open.Run(link) if err != nil { err = fmt.Errorf("could not open Docker Desktop") lk.keyboardError("View", err) } return err })() }() } func (lk *LogKeyboard) openDDComposeUI(ctx context.Context, project *types.Project) { if !lk.IsDockerDesktopActive { return } go func() { _ = tracing.EventWrapFuncForErrGroup(ctx, "menu/gui/composeview", tracing.SpanOptions{}, func(ctx context.Context) error { link := fmt.Sprintf("docker-desktop://dashboard/docker-compose/%s", project.Name) err := open.Run(link) if err != nil { err = fmt.Errorf("could not open Docker Desktop Compose UI") lk.keyboardError("View Config", err) } return err })() }() } func (lk *LogKeyboard) openDDWatchDocs(ctx context.Context, project *types.Project) { go func() { _ = tracing.EventWrapFuncForErrGroup(ctx, "menu/gui/watch", tracing.SpanOptions{}, func(ctx context.Context) error { link := fmt.Sprintf("docker-desktop://dashboard/docker-compose/%s/watch", project.Name) err := open.Run(link) if err != nil { err = fmt.Errorf("could not open Docker Desktop Compose UI") lk.keyboardError("Watch Docs", err) } return err })() }() } func (lk *LogKeyboard) keyboardError(prefix string, err error) { lk.kError.addError(prefix, err) lk.printNavigationMenu() timer1 := time.NewTimer((DISPLAY_ERROR_TIME + 1) * time.Second) go func() { <-timer1.C lk.printNavigationMenu() }() } func (lk *LogKeyboard) ToggleWatch(ctx context.Context, options api.UpOptions) { if lk.Watch == nil { return } if lk.Watch.Watching { err := lk.Watch.Watcher.Stop() if err != nil { options.Start.Attach.Err(api.WatchLogger, err.Error()) } else { lk.Watch.Watching = false } } else { go func() { _ = tracing.EventWrapFuncForErrGroup(ctx, "menu/watch", tracing.SpanOptions{}, func(ctx context.Context) error { err := lk.Watch.Watcher.Start(ctx) if err != nil { options.Start.Attach.Err(api.WatchLogger, err.Error()) } else { lk.Watch.Watching = true } return err })() }() } } func (lk *LogKeyboard) HandleKeyEvents(ctx context.Context, event keyboard.KeyEvent, project *types.Project, options api.UpOptions) { switch kRune := event.Rune; kRune { case 'd': lk.clearNavigationMenu() lk.Detach() case 'v': lk.openDockerDesktop(ctx, project) case 'w': if lk.Watch == nil { // we try to open watch docs if DD is installed if lk.IsDockerDesktopActive { lk.openDDWatchDocs(ctx, project) } // either way we mark menu/watch as an error go func() { _ = tracing.EventWrapFuncForErrGroup(ctx, "menu/watch", tracing.SpanOptions{}, func(ctx context.Context) error { err := fmt.Errorf("watch is not yet configured. Learn more: %s", ansiColor(CYAN, "https://docs.docker.com/compose/file-watch/")) lk.keyboardError("Watch", err) return err })() }() } lk.ToggleWatch(ctx, options) case 'o': lk.openDDComposeUI(ctx, project) } switch key := event.Key; key { case keyboard.KeyCtrlC: _ = keyboard.Close() lk.clearNavigationMenu() showCursor() lk.logLevel = NONE // will notify main thread to kill and will handle gracefully lk.signalChannel <- syscall.SIGINT case keyboard.KeyCtrlZ: handleCtrlZ() case keyboard.KeyEnter: newLine() lk.printNavigationMenu() } } func (lk *LogKeyboard) EnableWatch(enabled bool, watcher Feature) { lk.Watch = &KeyboardWatch{ Watching: enabled, Watcher: watcher, } } func (lk *LogKeyboard) EnableDetach(detach func()) { lk.Detach = detach } func allocateSpace(lines int) { for i := 0; i < lines; i++ { clearLine() newLine() carriageReturn() } } func extraLines(s string) int { return int(math.Floor(float64(lenAnsi(s)) / float64(goterm.Width()))) } func shortcutKeyColor(key string) string { foreground := "38;2" black := "0;0;0" background := "48;2" white := "255;255;255" return ansiColor(foreground+";"+black+";"+background+";"+white, key, BOLD) } func navColor(key string) string { return ansiColor(FAINT, key) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/formatter/ansi.go
cmd/formatter/ansi.go
/* Copyright 2024 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 formatter import ( "fmt" "github.com/acarl005/stripansi" "github.com/morikuni/aec" ) var disableAnsi bool func saveCursor() { if disableAnsi { return } // see https://github.com/morikuni/aec/pull/5 fmt.Print(aec.Save) } func restoreCursor() { if disableAnsi { return } // see https://github.com/morikuni/aec/pull/5 fmt.Print(aec.Restore) } func showCursor() { if disableAnsi { return } fmt.Print(aec.Show) } func moveCursor(y, x int) { if disableAnsi { return } fmt.Print(aec.Position(uint(y), uint(x))) } func carriageReturn() { if disableAnsi { return } fmt.Print(aec.Column(0)) } func clearLine() { if disableAnsi { return } // Does not move cursor from its current position fmt.Print(aec.EraseLine(aec.EraseModes.Tail)) } func moveCursorUp(lines int) { if disableAnsi { return } // Does not add new lines fmt.Print(aec.Up(uint(lines))) } func moveCursorDown(lines int) { if disableAnsi { return } // Does not add new lines fmt.Print(aec.Down(uint(lines))) } func newLine() { // Like \n fmt.Print("\012") } func lenAnsi(s string) int { // len has into consideration ansi codes, if we want // the len of the actual len(string) we need to strip // all ansi codes return len(stripansi.Strip(s)) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/json.go
cmd/display/json.go
/* Copyright 2024 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 display import ( "context" "encoding/json" "fmt" "io" "github.com/docker/compose/v5/pkg/api" ) func JSON(out io.Writer) api.EventProcessor { return &jsonWriter{ out: out, } } type jsonWriter struct { out io.Writer dryRun bool } type jsonMessage struct { DryRun bool `json:"dry-run,omitempty"` Tail bool `json:"tail,omitempty"` ID string `json:"id,omitempty"` ParentID string `json:"parent_id,omitempty"` Status string `json:"status,omitempty"` Text string `json:"text,omitempty"` Details string `json:"details,omitempty"` Current int64 `json:"current,omitempty"` Total int64 `json:"total,omitempty"` Percent int `json:"percent,omitempty"` } func (p *jsonWriter) Start(ctx context.Context, operation string) { } func (p *jsonWriter) Event(e api.Resource) { message := &jsonMessage{ DryRun: p.dryRun, Tail: false, ID: e.ID, Status: e.StatusText(), Text: e.Text, Details: e.Details, ParentID: e.ParentID, Current: e.Current, Total: e.Total, Percent: e.Percent, } marshal, err := json.Marshal(message) if err == nil { _, _ = fmt.Fprintln(p.out, string(marshal)) } } func (p *jsonWriter) On(events ...api.Resource) { for _, e := range events { p.Event(e) } } func (p *jsonWriter) Done(_ string, _ bool) { }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/json_test.go
cmd/display/json_test.go
/* Copyright 2024 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 display import ( "bytes" "encoding/json" "testing" "gotest.tools/v3/assert" "github.com/docker/compose/v5/pkg/api" ) func TestJsonWriter_Event(t *testing.T) { var out bytes.Buffer w := &jsonWriter{ out: &out, dryRun: true, } event := api.Resource{ ID: "service1", ParentID: "project", Status: api.Working, Text: api.StatusCreating, Current: 50, Total: 100, Percent: 50, } w.Event(event) var actual jsonMessage err := json.Unmarshal(out.Bytes(), &actual) assert.NilError(t, err) expected := jsonMessage{ DryRun: true, ID: event.ID, ParentID: event.ParentID, Text: api.StatusCreating, Status: "Working", Current: event.Current, Total: event.Total, Percent: event.Percent, } assert.DeepEqual(t, expected, actual) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/plain.go
cmd/display/plain.go
/* 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 display import ( "context" "fmt" "io" "github.com/docker/compose/v5/pkg/api" ) func Plain(out io.Writer) api.EventProcessor { return &plainWriter{ out: out, } } type plainWriter struct { out io.Writer dryRun bool } func (p *plainWriter) Start(ctx context.Context, operation string) { } func (p *plainWriter) Event(e api.Resource) { prefix := "" if p.dryRun { prefix = DRYRUN_PREFIX } _, _ = fmt.Fprintln(p.out, prefix, e.ID, e.Text, e.Details) } func (p *plainWriter) On(events ...api.Resource) { for _, e := range events { p.Event(e) } } func (p *plainWriter) Done(_ string, _ bool) { }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/tty.go
cmd/display/tty.go
/* 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 display import ( "context" "fmt" "io" "iter" "strings" "sync" "time" "github.com/buger/goterm" "github.com/docker/go-units" "github.com/morikuni/aec" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/utils" ) // Full creates an EventProcessor that render advanced UI within a terminal. // On Start, TUI lists task with a progress timer func Full(out io.Writer, info io.Writer) api.EventProcessor { return &ttyWriter{ out: out, info: info, tasks: map[string]*task{}, done: make(chan bool), mtx: &sync.Mutex{}, } } type ttyWriter struct { out io.Writer ids []string // tasks ids ordered as first event appeared tasks map[string]*task repeated bool numLines int done chan bool mtx *sync.Mutex dryRun bool // FIXME(ndeloof) (re)implement support for dry-run operation string ticker *time.Ticker suspended bool info io.Writer } type task struct { ID string parent string // the resource this task receives updates from - other parents will be ignored parents utils.Set[string] // all resources to depend on this task startTime time.Time endTime time.Time text string details string status api.EventStatus current int64 percent int total int64 spinner *Spinner } func newTask(e api.Resource) task { t := task{ ID: e.ID, parents: utils.NewSet[string](), startTime: time.Now(), text: e.Text, details: e.Details, status: e.Status, current: e.Current, percent: e.Percent, total: e.Total, spinner: NewSpinner(), } if e.ParentID != "" { t.parent = e.ParentID t.parents.Add(e.ParentID) } if e.Status == api.Done || e.Status == api.Error { t.stop() } return t } // update adjusts task state based on last received event func (t *task) update(e api.Resource) { if e.ParentID != "" { t.parents.Add(e.ParentID) // we may receive same event from distinct parents (typically: images sharing layers) // to avoid status to flicker, only accept updates from our first declared parent if t.parent != e.ParentID { return } } // update task based on received event switch e.Status { case api.Done, api.Error, api.Warning: if t.status != e.Status { t.stop() } case api.Working: t.hasMore() } t.status = e.Status t.text = e.Text t.details = e.Details // progress can only go up if e.Total > t.total { t.total = e.Total } if e.Current > t.current { t.current = e.Current } if e.Percent > t.percent { t.percent = e.Percent } } func (t *task) stop() { t.endTime = time.Now() t.spinner.Stop() } func (t *task) hasMore() { t.spinner.Restart() } func (t *task) Completed() bool { switch t.status { case api.Done, api.Error, api.Warning: return true default: return false } } func (w *ttyWriter) Start(ctx context.Context, operation string) { w.ticker = time.NewTicker(100 * time.Millisecond) w.operation = operation go func() { for { select { case <-ctx.Done(): // interrupted w.ticker.Stop() return case <-w.done: return case <-w.ticker.C: w.print() } } }() } func (w *ttyWriter) Done(operation string, success bool) { w.print() w.mtx.Lock() defer w.mtx.Unlock() w.ticker.Stop() w.operation = "" w.done <- true } func (w *ttyWriter) On(events ...api.Resource) { w.mtx.Lock() defer w.mtx.Unlock() for _, e := range events { if e.ID == "Compose" { _, _ = fmt.Fprintln(w.info, ErrorColor(e.Details)) continue } if w.operation != "start" && (e.Text == api.StatusStarted || e.Text == api.StatusStarting) { // skip those events to avoid mix with container logs continue } w.event(e) } } func (w *ttyWriter) event(e api.Resource) { // Suspend print while a build is in progress, to avoid collision with buildkit Display if e.Text == api.StatusBuilding { w.ticker.Stop() w.suspended = true } else if w.suspended { w.ticker.Reset(100 * time.Millisecond) w.suspended = false } if last, ok := w.tasks[e.ID]; ok { last.update(e) } else { t := newTask(e) w.tasks[e.ID] = &t w.ids = append(w.ids, e.ID) } w.printEvent(e) } func (w *ttyWriter) printEvent(e api.Resource) { if w.operation != "" { // event will be displayed by progress UI on ticker's ticks return } var color colorFunc switch e.Status { case api.Working: color = SuccessColor case api.Done: color = SuccessColor case api.Warning: color = WarningColor case api.Error: color = ErrorColor } _, _ = fmt.Fprintf(w.out, "%s %s %s\n", e.ID, color(e.Text), e.Details) } func (w *ttyWriter) parentTasks() iter.Seq[*task] { return func(yield func(*task) bool) { for _, id := range w.ids { // iterate on ids to enforce a consistent order t := w.tasks[id] if len(t.parents) == 0 { yield(t) } } } } func (w *ttyWriter) childrenTasks(parent string) iter.Seq[*task] { return func(yield func(*task) bool) { for _, id := range w.ids { // iterate on ids to enforce a consistent order t := w.tasks[id] if t.parents.Has(parent) { yield(t) } } } } func (w *ttyWriter) print() { w.mtx.Lock() defer w.mtx.Unlock() if len(w.tasks) == 0 { return } terminalWidth := goterm.Width() up := w.numLines + 1 if !w.repeated { up-- w.repeated = true } b := aec.NewBuilder( aec.Hide, // Hide the cursor while we are printing aec.Up(uint(up)), aec.Column(0), ) _, _ = fmt.Fprint(w.out, b.ANSI) defer func() { _, _ = fmt.Fprint(w.out, aec.Show) }() firstLine := fmt.Sprintf("[+] %s %d/%d", w.operation, numDone(w.tasks), len(w.tasks)) _, _ = fmt.Fprintln(w.out, firstLine) var statusPadding int for _, t := range w.tasks { l := len(t.ID) if len(t.parents) == 0 && statusPadding < l { statusPadding = l } } skipChildEvents := len(w.tasks) > goterm.Height()-2 numLines := 0 for t := range w.parentTasks() { line := w.lineText(t, "", terminalWidth, statusPadding, w.dryRun) _, _ = fmt.Fprint(w.out, line) numLines++ if skipChildEvents { continue } for child := range w.childrenTasks(t.ID) { line := w.lineText(child, " ", terminalWidth, statusPadding-2, w.dryRun) _, _ = fmt.Fprint(w.out, line) numLines++ } } for i := numLines; i < w.numLines; i++ { if numLines < goterm.Height()-2 { _, _ = fmt.Fprintln(w.out, strings.Repeat(" ", terminalWidth)) numLines++ } } w.numLines = numLines } func (w *ttyWriter) lineText(t *task, pad string, terminalWidth, statusPadding int, dryRun bool) string { endTime := time.Now() if t.status != api.Working { endTime = t.startTime if (t.endTime != time.Time{}) { endTime = t.endTime } } prefix := "" if dryRun { prefix = PrefixColor(DRYRUN_PREFIX) } elapsed := endTime.Sub(t.startTime).Seconds() var ( hideDetails bool total int64 current int64 completion []string ) // only show the aggregated progress while the root operation is in-progress if parent := t; parent.status == api.Working { for child := range w.childrenTasks(parent.ID) { if child.status == api.Working && child.total == 0 { // we don't have totals available for all the child events // so don't show the total progress yet hideDetails = true } total += child.total current += child.current r := len(percentChars) - 1 p := child.percent if p > 100 { p = 100 } completion = append(completion, percentChars[r*p/100]) } } // don't try to show detailed progress if we don't have any idea if total == 0 { hideDetails = true } txt := t.ID if len(completion) > 0 { var progress string if !hideDetails { progress = fmt.Sprintf(" %7s / %-7s", units.HumanSize(float64(current)), units.HumanSize(float64(total))) } txt = fmt.Sprintf("%s [%s]%s", t.ID, SuccessColor(strings.Join(completion, "")), progress, ) } textLen := len(txt) padding := statusPadding - textLen if padding < 0 { padding = 0 } // calculate the max length for the status text, on errors it // is 2-3 lines long and breaks the line formatting maxDetailsLen := terminalWidth - textLen - statusPadding - 15 details := t.details // in some cases (debugging under VS Code), terminalWidth is set to zero by goterm.Width() ; ensuring we don't tweak strings with negative char index if maxDetailsLen > 0 && len(details) > maxDetailsLen { details = details[:maxDetailsLen] + "..." } text := fmt.Sprintf("%s %s%s %s %s%s %s", pad, spinner(t), prefix, txt, strings.Repeat(" ", padding), colorFn(t.status)(t.text), details, ) timer := fmt.Sprintf("%.1fs ", elapsed) o := align(text, TimerColor(timer), terminalWidth) return o } var ( spinnerDone = "✔" spinnerWarning = "!" spinnerError = "✘" ) func spinner(t *task) string { switch t.status { case api.Done: return SuccessColor(spinnerDone) case api.Warning: return WarningColor(spinnerWarning) case api.Error: return ErrorColor(spinnerError) default: return CountColor(t.spinner.String()) } } func colorFn(s api.EventStatus) colorFunc { switch s { case api.Done: return SuccessColor case api.Warning: return WarningColor case api.Error: return ErrorColor default: return nocolor } } func numDone(tasks map[string]*task) int { i := 0 for _, t := range tasks { if t.status != api.Working { i++ } } return i } func align(l, r string, w int) string { ll := lenAnsi(l) lr := lenAnsi(r) pad := "" count := w - ll - lr if count > 0 { pad = strings.Repeat(" ", count) } return fmt.Sprintf("%s%s%s\n", l, pad, r) } // lenAnsi count of user-perceived characters in ANSI string. func lenAnsi(s string) int { length := 0 ansiCode := false for _, r := range s { if r == '\x1b' { ansiCode = true continue } if ansiCode && r == 'm' { ansiCode = false continue } if !ansiCode { length++ } } return length } var percentChars = strings.Split("⠀⡀⣀⣄⣤⣦⣶⣷⣿", "")
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/quiet.go
cmd/display/quiet.go
/* 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 display import ( "context" "github.com/docker/compose/v5/pkg/api" ) func Quiet() api.EventProcessor { return &quiet{} } type quiet struct{} func (q *quiet) Start(_ context.Context, _ string) { } func (q *quiet) Done(_ string, _ bool) { } func (q *quiet) On(_ ...api.Resource) { }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/mode.go
cmd/display/mode.go
/* Copyright 2024 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 display // Mode define how progress should be rendered, either as ModePlain or ModeTTY var Mode = ModeAuto const ( // ModeAuto detect console capabilities ModeAuto = "auto" // ModeTTY use terminal capability for advanced rendering ModeTTY = "tty" // ModePlain dump raw events to output ModePlain = "plain" // ModeQuiet don't display events ModeQuiet = "quiet" // ModeJSON outputs a machine-readable JSON stream ModeJSON = "json" )
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/spinner.go
cmd/display/spinner.go
/* 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 display import ( "runtime" "time" ) type Spinner struct { time time.Time index int chars []string stop bool done string } func NewSpinner() *Spinner { chars := []string{ "⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏", } done := "⠿" if runtime.GOOS == "windows" { chars = []string{"-"} done = "-" } return &Spinner{ index: 0, time: time.Now(), chars: chars, done: done, } } func (s *Spinner) String() string { if s.stop { return s.done } d := time.Since(s.time) if d.Milliseconds() > 100 { s.index = (s.index + 1) % len(s.chars) } return s.chars[s.index] } func (s *Spinner) Stop() { s.stop = true } func (s *Spinner) Restart() { s.stop = false }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/colors.go
cmd/display/colors.go
/* 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 display import ( "github.com/morikuni/aec" ) type colorFunc func(string) string var ( nocolor colorFunc = func(s string) string { return s } DoneColor colorFunc = aec.BlueF.Apply TimerColor colorFunc = aec.BlueF.Apply CountColor colorFunc = aec.YellowF.Apply WarningColor colorFunc = aec.YellowF.With(aec.Bold).Apply SuccessColor colorFunc = aec.GreenF.Apply ErrorColor colorFunc = aec.RedF.With(aec.Bold).Apply PrefixColor colorFunc = aec.CyanF.Apply ) func NoColor() { DoneColor = nocolor TimerColor = nocolor CountColor = nocolor WarningColor = nocolor SuccessColor = nocolor ErrorColor = nocolor PrefixColor = nocolor }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/display/dryrun.go
cmd/display/dryrun.go
/* 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 display const ( DRYRUN_PREFIX = " DRY-RUN MODE - " )
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/prompt/prompt.go
cmd/prompt/prompt.go
/* 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 prompt import ( "fmt" "io" "github.com/AlecAivazis/survey/v2" "github.com/docker/cli/cli/streams" "github.com/docker/compose/v5/pkg/utils" ) //go:generate mockgen -destination=./prompt_mock.go -self_package "github.com/docker/compose/v5/pkg/prompt" -package=prompt . UI // UI - prompt user input type UI interface { Confirm(message string, defaultValue bool) (bool, error) } func NewPrompt(stdin *streams.In, stdout *streams.Out) UI { if stdin.IsTerminal() { return User{stdin: streamsFileReader{stdin}, stdout: streamsFileWriter{stdout}} } return Pipe{stdin: stdin, stdout: stdout} } // User - in a terminal type User struct { stdout streamsFileWriter stdin streamsFileReader } // adapt streams.Out to terminal.FileWriter type streamsFileWriter struct { stream *streams.Out } func (s streamsFileWriter) Write(p []byte) (n int, err error) { return s.stream.Write(p) } func (s streamsFileWriter) Fd() uintptr { return s.stream.FD() } // adapt streams.In to terminal.FileReader type streamsFileReader struct { stream *streams.In } func (s streamsFileReader) Read(p []byte) (n int, err error) { return s.stream.Read(p) } func (s streamsFileReader) Fd() uintptr { return s.stream.FD() } // Confirm asks for yes or no input func (u User) Confirm(message string, defaultValue bool) (bool, error) { qs := &survey.Confirm{ Message: message, Default: defaultValue, } var b bool err := survey.AskOne(qs, &b, func(options *survey.AskOptions) error { options.Stdio.In = u.stdin options.Stdio.Out = u.stdout return nil }) return b, err } // Pipe - aggregates prompt methods type Pipe struct { stdout io.Writer stdin io.Reader } // Confirm asks for yes or no input func (u Pipe) Confirm(message string, defaultValue bool) (bool, error) { _, _ = fmt.Fprint(u.stdout, message) var answer string _, _ = fmt.Fscanln(u.stdin, &answer) return utils.StringToBool(answer), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/prompt/prompt_mock.go
cmd/prompt/prompt_mock.go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/docker/compose-cli/pkg/prompt (interfaces: UI) // Package prompt is a generated GoMock package. package prompt import ( reflect "reflect" gomock "go.uber.org/mock/gomock" ) // MockUI is a mock of UI interface type MockUI struct { ctrl *gomock.Controller recorder *MockUIMockRecorder } // MockUIMockRecorder is the mock recorder for MockUI type MockUIMockRecorder struct { mock *MockUI } // NewMockUI creates a new mock instance func NewMockUI(ctrl *gomock.Controller) *MockUI { mock := &MockUI{ctrl: ctrl} mock.recorder = &MockUIMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockUI) EXPECT() *MockUIMockRecorder { return m.recorder } // Confirm mocks base method func (m *MockUI) Confirm(arg0 string, arg1 bool) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Confirm", arg0, arg1) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // Confirm indicates an expected call of Confirm func (mr *MockUIMockRecorder) Confirm(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Confirm", reflect.TypeOf((*MockUI)(nil).Confirm), arg0, arg1) } // Input mocks base method func (m *MockUI) Input(arg0, arg1 string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Input", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // Input indicates an expected call of Input func (mr *MockUIMockRecorder) Input(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Input", reflect.TypeOf((*MockUI)(nil).Input), arg0, arg1) } // Password mocks base method func (m *MockUI) Password(arg0 string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Password", arg0) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // Password indicates an expected call of Password func (mr *MockUIMockRecorder) Password(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Password", reflect.TypeOf((*MockUI)(nil).Password), arg0) } // Select mocks base method func (m *MockUI) Select(arg0 string, arg1 []string) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Select", arg0, arg1) ret0, _ := ret[0].(int) ret1, _ := ret[1].(error) return ret0, ret1 } // Select indicates an expected call of Select func (mr *MockUIMockRecorder) Select(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Select", reflect.TypeOf((*MockUI)(nil).Select), arg0, arg1) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/start.go
cmd/compose/start.go
/* 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 ( "context" "time" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type startOptions struct { *ProjectOptions wait bool waitTimeout int } func startCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := startOptions{ ProjectOptions: p, } startCmd := &cobra.Command{ Use: "start [SERVICE...]", Short: "Start services", RunE: Adapt(func(ctx context.Context, args []string) error { return runStart(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := startCmd.Flags() flags.BoolVar(&opts.wait, "wait", false, "Wait for services to be running|healthy. Implies detached mode.") flags.IntVar(&opts.waitTimeout, "wait-timeout", 0, "Maximum duration in seconds to wait for the project to be running|healthy") return startCmd } func runStart(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts startOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } var timeout time.Duration if opts.waitTimeout > 0 { timeout = time.Duration(opts.waitTimeout) * time.Second } return backend.Start(ctx, name, api.StartOptions{ AttachTo: services, Project: project, Services: services, Wait: opts.wait, WaitTimeout: timeout, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/exec.go
cmd/compose/exec.go
/* 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 ( "context" "errors" "fmt" "os" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type execOpts struct { *composeOptions service string command []string environment []string workingDir string noTty bool user string detach bool index int privileged bool interactive bool } func execCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := execOpts{ composeOptions: &composeOptions{ ProjectOptions: p, }, } runCmd := &cobra.Command{ Use: "exec [OPTIONS] SERVICE COMMAND [ARGS...]", Short: "Execute a command in a running container", Args: cobra.MinimumNArgs(2), PreRunE: Adapt(func(ctx context.Context, args []string) error { opts.service = args[0] opts.command = args[1:] return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { err := runExec(ctx, dockerCli, backendOptions, opts) if err != nil { logrus.Debugf("%v", err) var cliError cli.StatusError if ok := errors.As(err, &cliError); ok { os.Exit(err.(cli.StatusError).StatusCode) //nolint: errorlint } } return err }), ValidArgsFunction: completeServiceNames(dockerCli, p), } runCmd.Flags().BoolVarP(&opts.detach, "detach", "d", false, "Detached mode: Run command in the background") runCmd.Flags().StringArrayVarP(&opts.environment, "env", "e", []string{}, "Set environment variables") runCmd.Flags().IntVar(&opts.index, "index", 0, "Index of the container if service has multiple replicas") runCmd.Flags().BoolVarP(&opts.privileged, "privileged", "", false, "Give extended privileges to the process") runCmd.Flags().StringVarP(&opts.user, "user", "u", "", "Run the command as this user") runCmd.Flags().BoolVarP(&opts.noTty, "no-tty", "T", !dockerCli.Out().IsTerminal(), "Disable pseudo-TTY allocation. By default 'docker compose exec' allocates a TTY.") runCmd.Flags().StringVarP(&opts.workingDir, "workdir", "w", "", "Path to workdir directory for this command") runCmd.Flags().BoolVarP(&opts.interactive, "interactive", "i", true, "Keep STDIN open even if not attached") runCmd.Flags().MarkHidden("interactive") //nolint:errcheck runCmd.Flags().BoolP("tty", "t", true, "Allocate a pseudo-TTY") runCmd.Flags().MarkHidden("tty") //nolint:errcheck runCmd.Flags().SetInterspersed(false) runCmd.Flags().SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName { if name == "no-TTY" { // legacy name = "no-tty" } return pflag.NormalizedName(name) }) return runCmd } func runExec(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts execOpts) error { projectName, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } projectOptions, err := opts.composeOptions.toProjectOptions() //nolint:staticcheck if err != nil { return err } lookupFn := func(k string) (string, bool) { v, ok := projectOptions.Environment[k] return v, ok } execOpts := api.RunOptions{ Service: opts.service, Command: opts.command, Environment: compose.ToMobyEnv(types.NewMappingWithEquals(opts.environment).Resolve(lookupFn)), Tty: !opts.noTty, User: opts.user, Privileged: opts.privileged, Index: opts.index, Detach: opts.detach, WorkingDir: opts.workingDir, Interactive: opts.interactive, } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } exitCode, err := backend.Exec(ctx, projectName, execOpts) if exitCode != 0 { errMsg := fmt.Sprintf("exit status %d", exitCode) if err != nil && err.Error() != "" { errMsg = err.Error() } return cli.StatusError{StatusCode: exitCode, Status: errMsg} } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/stop.go
cmd/compose/stop.go
/* 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 ( "context" "time" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type stopOptions struct { *ProjectOptions timeChanged bool timeout int } func stopCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := stopOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "stop [OPTIONS] [SERVICE...]", Short: "Stop services", PreRun: func(cmd *cobra.Command, args []string) { opts.timeChanged = cmd.Flags().Changed("timeout") }, RunE: Adapt(func(ctx context.Context, args []string) error { return runStop(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.IntVarP(&opts.timeout, "timeout", "t", 0, "Specify a shutdown timeout in seconds") return cmd } func runStop(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts stopOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } var timeout *time.Duration if opts.timeChanged { timeoutValue := time.Duration(opts.timeout) * time.Second timeout = &timeoutValue } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Stop(ctx, name, api.StopOptions{ Timeout: timeout, Services: services, Project: project, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/commit.go
cmd/compose/commit.go
/* 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 ( "context" "github.com/docker/cli/cli/command" "github.com/docker/cli/opts" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type commitOptions struct { *ProjectOptions service string reference string pause bool comment string author string changes opts.ListOpts index int } func commitCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { options := commitOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "commit [OPTIONS] SERVICE [REPOSITORY[:TAG]]", Short: "Create a new image from a service container's changes", Args: cobra.RangeArgs(1, 2), PreRunE: Adapt(func(ctx context.Context, args []string) error { options.service = args[0] if len(args) > 1 { options.reference = args[1] } return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { return runCommit(ctx, dockerCli, backendOptions, options) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.IntVar(&options.index, "index", 0, "index of the container if service has multiple replicas.") flags.BoolVarP(&options.pause, "pause", "p", true, "Pause container during commit") flags.StringVarP(&options.comment, "message", "m", "", "Commit message") flags.StringVarP(&options.author, "author", "a", "", `Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")`) options.changes = opts.NewListOpts(nil) flags.VarP(&options.changes, "change", "c", "Apply Dockerfile instruction to the created image") return cmd } func runCommit(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, options commitOptions) error { projectName, err := options.toProjectName(ctx, dockerCli) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Commit(ctx, projectName, api.CommitOptions{ Service: options.service, Reference: options.reference, Pause: options.pause, Comment: options.comment, Author: options.author, Changes: options.changes, Index: options.index, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/create.go
cmd/compose/create.go
/* 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 ( "context" "fmt" "slices" "strconv" "strings" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type createOptions struct { Build bool noBuild bool Pull string pullChanged bool removeOrphans bool ignoreOrphans bool forceRecreate bool noRecreate bool recreateDeps bool noInherit bool timeChanged bool timeout int quietPull bool scale []string AssumeYes bool } func createCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := createOptions{} buildOpts := buildOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "create [OPTIONS] [SERVICE...]", Short: "Creates containers for a service", PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { opts.pullChanged = cmd.Flags().Changed("pull") if opts.Build && opts.noBuild { return fmt.Errorf("--build and --no-build are incompatible") } if opts.forceRecreate && opts.noRecreate { return fmt.Errorf("--force-recreate and --no-recreate are incompatible") } return nil }), RunE: p.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error { return runCreate(ctx, dockerCli, backendOptions, opts, buildOpts, project, services) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.BoolVar(&opts.Build, "build", false, "Build images before starting containers") flags.BoolVar(&opts.noBuild, "no-build", false, "Don't build an image, even if it's policy") flags.StringVar(&opts.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never"|"build")`) flags.BoolVar(&opts.quietPull, "quiet-pull", false, "Pull without printing progress information") flags.BoolVar(&opts.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed") flags.BoolVar(&opts.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.") flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file") flags.StringArrayVar(&opts.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.") flags.BoolVarP(&opts.AssumeYes, "yes", "y", false, `Assume "yes" as answer to all prompts and run non-interactively`) flags.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName { // assumeYes was introduced by mistake as `--y` if name == "y" { logrus.Warn("--y is deprecated, please use --yes instead") name = "yes" } return pflag.NormalizedName(name) }) return cmd } func runCreate(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, createOpts createOptions, buildOpts buildOptions, project *types.Project, services []string) error { if err := createOpts.Apply(project); err != nil { return err } var build *api.BuildOptions if !createOpts.noBuild { bo, err := buildOpts.toAPIBuildOptions(services) if err != nil { return err } build = &bo } if createOpts.AssumeYes { backendOptions.Options = append(backendOptions.Options, compose.WithPrompt(compose.AlwaysOkPrompt())) } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Create(ctx, project, api.CreateOptions{ Build: build, Services: services, RemoveOrphans: createOpts.removeOrphans, IgnoreOrphans: createOpts.ignoreOrphans, Recreate: createOpts.recreateStrategy(), RecreateDependencies: createOpts.dependenciesRecreateStrategy(), Inherit: !createOpts.noInherit, Timeout: createOpts.GetTimeout(), QuietPull: createOpts.quietPull, }) } func (opts createOptions) recreateStrategy() string { if opts.noRecreate { return api.RecreateNever } if opts.forceRecreate { return api.RecreateForce } if opts.noInherit { return api.RecreateForce } return api.RecreateDiverged } func (opts createOptions) dependenciesRecreateStrategy() string { if opts.noRecreate { return api.RecreateNever } if opts.recreateDeps { return api.RecreateForce } return api.RecreateDiverged } func (opts createOptions) GetTimeout() *time.Duration { if opts.timeChanged { t := time.Duration(opts.timeout) * time.Second return &t } return nil } func (opts createOptions) Apply(project *types.Project) error { if opts.pullChanged { if !opts.isPullPolicyValid() { return fmt.Errorf("invalid --pull option %q", opts.Pull) } for i, service := range project.Services { service.PullPolicy = opts.Pull project.Services[i] = service } } // N.B. opts.Build means "force build all", but images can still be built // when this is false // e.g. if a service has pull_policy: build or its local image is policy if opts.Build { for i, service := range project.Services { if service.Build == nil { continue } service.PullPolicy = types.PullPolicyBuild project.Services[i] = service } } if err := applyPlatforms(project, true); err != nil { return err } err := applyScaleOpts(project, opts.scale) if err != nil { return err } return nil } func applyScaleOpts(project *types.Project, opts []string) error { for _, scale := range opts { split := strings.Split(scale, "=") if len(split) != 2 { return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale) } name := split[0] replicas, err := strconv.Atoi(split[1]) if err != nil { return err } err = setServiceScale(project, name, replicas) if err != nil { return err } } return nil } func (opts createOptions) isPullPolicyValid() bool { pullPolicies := []string{ types.PullPolicyAlways, types.PullPolicyNever, types.PullPolicyBuild, types.PullPolicyMissing, types.PullPolicyIfNotPresent, } return slices.Contains(pullPolicies, opts.Pull) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/stats.go
cmd/compose/stats.go
/* 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 ( "context" "fmt" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command/container" "github.com/docker/docker/api/types/filters" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" ) type statsOptions struct { ProjectOptions *ProjectOptions all bool format string noStream bool noTrunc bool } func statsCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command { opts := statsOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "stats [OPTIONS] [SERVICE]", Short: "Display a live stream of container(s) resource usage statistics", Args: cobra.MaximumNArgs(1), RunE: Adapt(func(ctx context.Context, args []string) error { return runStats(ctx, dockerCli, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.BoolVarP(&opts.all, "all", "a", false, "Show all containers (default shows just running)") flags.StringVar(&opts.format, "format", "", `Format output using a custom template: 'table': Print output in table format with column headers (default) 'table TEMPLATE': Print output in table format using the given Go template 'json': Print in JSON format 'TEMPLATE': Print output using the given Go template. Refer to https://docs.docker.com/engine/cli/formatting/ for more information about formatting output with templates`) flags.BoolVar(&opts.noStream, "no-stream", false, "Disable streaming stats and only pull the first result") flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate output") return cmd } func runStats(ctx context.Context, dockerCli command.Cli, opts statsOptions, service []string) error { name, err := opts.ProjectOptions.toProjectName(ctx, dockerCli) if err != nil { return err } filter := []filters.KeyValuePair{ filters.Arg("label", fmt.Sprintf("%s=%s", api.ProjectLabel, name)), } if len(service) > 0 { filter = append(filter, filters.Arg("label", fmt.Sprintf("%s=%s", api.ServiceLabel, service[0]))) } args := filters.NewArgs(filter...) return container.RunStats(ctx, dockerCli, &container.StatsOptions{ All: opts.all, NoStream: opts.noStream, NoTrunc: opts.noTrunc, Format: opts.format, Filters: &args, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/compose_test.go
cmd/compose/compose_test.go
/* 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 ( "testing" "github.com/compose-spec/compose-go/v2/types" "gotest.tools/v3/assert" ) func TestFilterServices(t *testing.T) { p := &types.Project{ Services: types.Services{ "foo": { Name: "foo", Links: []string{"bar"}, }, "bar": { Name: "bar", DependsOn: map[string]types.ServiceDependency{ "zot": {}, }, }, "zot": { Name: "zot", }, "qix": { Name: "qix", }, }, } p, err := p.WithSelectedServices([]string{"bar"}) assert.NilError(t, err) assert.Equal(t, len(p.Services), 2) _, err = p.GetService("bar") assert.NilError(t, err) _, err = p.GetService("zot") assert.NilError(t, err) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/kill.go
cmd/compose/kill.go
/* 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 ( "context" "errors" "fmt" "os" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" "github.com/docker/compose/v5/pkg/utils" ) type killOptions struct { *ProjectOptions removeOrphans bool signal string } func killCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := killOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "kill [OPTIONS] [SERVICE...]", Short: "Force stop service containers", RunE: Adapt(func(ctx context.Context, args []string) error { return runKill(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() removeOrphans := utils.StringToBool(os.Getenv(ComposeRemoveOrphans)) flags.BoolVar(&opts.removeOrphans, "remove-orphans", removeOrphans, "Remove containers for services not defined in the Compose file") flags.StringVarP(&opts.signal, "signal", "s", "SIGKILL", "SIGNAL to send to the container") return cmd } func runKill(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts killOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } err = backend.Kill(ctx, name, api.KillOptions{ RemoveOrphans: opts.removeOrphans, Project: project, Services: services, Signal: opts.signal, }) if errors.Is(err, api.ErrNoResources) { _, _ = fmt.Fprintln(stdinfo(dockerCli), "No container to kill") return nil } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/top_test.go
cmd/compose/top_test.go
/* Copyright 2024 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 ( "bytes" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/docker/compose/v5/pkg/api" ) var topTestCases = []struct { name string titles []string procs [][]string header topHeader entries []topEntries output string }{ { name: "noprocs", titles: []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, procs: [][]string{}, header: topHeader{"SERVICE": 0, "#": 1}, entries: []topEntries{}, output: "", }, { name: "simple", titles: []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, procs: [][]string{{"root", "1", "1", "0", "12:00", "?", "00:00:01", "/entrypoint"}}, header: topHeader{ "SERVICE": 0, "#": 1, "UID": 2, "PID": 3, "PPID": 4, "C": 5, "STIME": 6, "TTY": 7, "TIME": 8, "CMD": 9, }, entries: []topEntries{ { "SERVICE": "simple", "#": "1", "UID": "root", "PID": "1", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:01", "CMD": "/entrypoint", }, }, output: trim(` SERVICE # UID PID PPID C STIME TTY TIME CMD simple 1 root 1 1 0 12:00 ? 00:00:01 /entrypoint `), }, { name: "noppid", titles: []string{"UID", "PID", "C", "STIME", "TTY", "TIME", "CMD"}, procs: [][]string{{"root", "1", "0", "12:00", "?", "00:00:02", "/entrypoint"}}, header: topHeader{ "SERVICE": 0, "#": 1, "UID": 2, "PID": 3, "C": 4, "STIME": 5, "TTY": 6, "TIME": 7, "CMD": 8, }, entries: []topEntries{ { "SERVICE": "noppid", "#": "1", "UID": "root", "PID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:02", "CMD": "/entrypoint", }, }, output: trim(` SERVICE # UID PID C STIME TTY TIME CMD noppid 1 root 1 0 12:00 ? 00:00:02 /entrypoint `), }, { name: "extra-hdr", titles: []string{"UID", "GID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, procs: [][]string{{"root", "1", "1", "1", "0", "12:00", "?", "00:00:03", "/entrypoint"}}, header: topHeader{ "SERVICE": 0, "#": 1, "UID": 2, "GID": 3, "PID": 4, "PPID": 5, "C": 6, "STIME": 7, "TTY": 8, "TIME": 9, "CMD": 10, }, entries: []topEntries{ { "SERVICE": "extra-hdr", "#": "1", "UID": "root", "GID": "1", "PID": "1", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:03", "CMD": "/entrypoint", }, }, output: trim(` SERVICE # UID GID PID PPID C STIME TTY TIME CMD extra-hdr 1 root 1 1 1 0 12:00 ? 00:00:03 /entrypoint `), }, { name: "multiple", titles: []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, procs: [][]string{ {"root", "1", "1", "0", "12:00", "?", "00:00:04", "/entrypoint"}, {"root", "123", "1", "0", "12:00", "?", "00:00:42", "sleep infinity"}, }, header: topHeader{ "SERVICE": 0, "#": 1, "UID": 2, "PID": 3, "PPID": 4, "C": 5, "STIME": 6, "TTY": 7, "TIME": 8, "CMD": 9, }, entries: []topEntries{ { "SERVICE": "multiple", "#": "1", "UID": "root", "PID": "1", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:04", "CMD": "/entrypoint", }, { "SERVICE": "multiple", "#": "1", "UID": "root", "PID": "123", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:42", "CMD": "sleep infinity", }, }, output: trim(` SERVICE # UID PID PPID C STIME TTY TIME CMD multiple 1 root 1 1 0 12:00 ? 00:00:04 /entrypoint multiple 1 root 123 1 0 12:00 ? 00:00:42 sleep infinity `), }, } // TestRunTopCore only tests the core functionality of runTop: formatting // and printing of the output of (api.Compose).Top(). func TestRunTopCore(t *testing.T) { t.Parallel() all := []api.ContainerProcSummary{} for _, tc := range topTestCases { summary := api.ContainerProcSummary{ Name: "not used", Titles: tc.titles, Processes: tc.procs, Service: tc.name, Replica: "1", } all = append(all, summary) t.Run(tc.name, func(t *testing.T) { header, entries := collectTop([]api.ContainerProcSummary{summary}) assert.Equal(t, tc.header, header) assert.Equal(t, tc.entries, entries) var buf bytes.Buffer err := topPrint(&buf, header, entries) require.NoError(t, err) assert.Equal(t, tc.output, buf.String()) }) } t.Run("all", func(t *testing.T) { header, entries := collectTop(all) assert.Equal(t, topHeader{ "SERVICE": 0, "#": 1, "UID": 2, "PID": 3, "PPID": 4, "C": 5, "STIME": 6, "TTY": 7, "TIME": 8, "GID": 9, "CMD": 10, }, header) assert.Equal(t, []topEntries{ { "SERVICE": "simple", "#": "1", "UID": "root", "PID": "1", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:01", "CMD": "/entrypoint", }, { "SERVICE": "noppid", "#": "1", "UID": "root", "PID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:02", "CMD": "/entrypoint", }, { "SERVICE": "extra-hdr", "#": "1", "UID": "root", "GID": "1", "PID": "1", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:03", "CMD": "/entrypoint", }, { "SERVICE": "multiple", "#": "1", "UID": "root", "PID": "1", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:04", "CMD": "/entrypoint", }, { "SERVICE": "multiple", "#": "1", "UID": "root", "PID": "123", "PPID": "1", "C": "0", "STIME": "12:00", "TTY": "?", "TIME": "00:00:42", "CMD": "sleep infinity", }, }, entries) var buf bytes.Buffer err := topPrint(&buf, header, entries) require.NoError(t, err) assert.Equal(t, trim(` SERVICE # UID PID PPID C STIME TTY TIME GID CMD simple 1 root 1 1 0 12:00 ? 00:00:01 - /entrypoint noppid 1 root 1 - 0 12:00 ? 00:00:02 - /entrypoint extra-hdr 1 root 1 1 0 12:00 ? 00:00:03 1 /entrypoint multiple 1 root 1 1 0 12:00 ? 00:00:04 - /entrypoint multiple 1 root 123 1 0 12:00 ? 00:00:42 - sleep infinity `), buf.String()) }) } func trim(s string) string { var out bytes.Buffer for line := range strings.SplitSeq(strings.TrimSpace(s), "\n") { out.WriteString(strings.TrimSpace(line)) out.WriteRune('\n') } return out.String() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/wait.go
cmd/compose/wait.go
/* Copyright 2023 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 ( "context" "os" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type waitOptions struct { *ProjectOptions services []string downProject bool } func waitCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := waitOptions{ ProjectOptions: p, } var statusCode int64 var err error cmd := &cobra.Command{ Use: "wait SERVICE [SERVICE...] [OPTIONS]", Short: "Block until containers of all (or specified) services stop.", Args: cli.RequiresMinArgs(1), RunE: Adapt(func(ctx context.Context, services []string) error { opts.services = services statusCode, err = runWait(ctx, dockerCli, backendOptions, &opts) return err }), PostRun: func(cmd *cobra.Command, args []string) { os.Exit(int(statusCode)) }, } cmd.Flags().BoolVar(&opts.downProject, "down-project", false, "Drops project when the first container stops") return cmd } func runWait(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts *waitOptions) (int64, error) { _, name, err := opts.projectOrName(ctx, dockerCli) if err != nil { return 0, err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return 0, err } return backend.Wait(ctx, name, api.WaitOptions{ Services: opts.services, DownProjectOnContainerExit: opts.downProject, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/down.go
cmd/compose/down.go
/* 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 ( "context" "fmt" "os" "time" "github.com/docker/cli/cli/command" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" "github.com/docker/compose/v5/pkg/utils" ) type downOptions struct { *ProjectOptions removeOrphans bool timeChanged bool timeout int volumes bool images string } func downCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := downOptions{ ProjectOptions: p, } downCmd := &cobra.Command{ Use: "down [OPTIONS] [SERVICES]", Short: "Stop and remove containers, networks", PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { opts.timeChanged = cmd.Flags().Changed("timeout") if opts.images != "" { if opts.images != "all" && opts.images != "local" { return fmt.Errorf("invalid value for --rmi: %q", opts.images) } } return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { return runDown(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := downCmd.Flags() removeOrphans := utils.StringToBool(os.Getenv(ComposeRemoveOrphans)) flags.BoolVar(&opts.removeOrphans, "remove-orphans", removeOrphans, "Remove containers for services not defined in the Compose file") flags.IntVarP(&opts.timeout, "timeout", "t", 0, "Specify a shutdown timeout in seconds") flags.BoolVarP(&opts.volumes, "volumes", "v", false, `Remove named volumes declared in the "volumes" section of the Compose file and anonymous volumes attached to containers`) flags.StringVar(&opts.images, "rmi", "", `Remove images used by services. "local" remove only images that don't have a custom tag ("local"|"all")`) flags.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName { if name == "volume" { name = "volumes" logrus.Warn("--volume is deprecated, please use --volumes") } return pflag.NormalizedName(name) }) return downCmd } func runDown(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts downOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } var timeout *time.Duration if opts.timeChanged { timeoutValue := time.Duration(opts.timeout) * time.Second timeout = &timeoutValue } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Down(ctx, name, api.DownOptions{ RemoveOrphans: opts.removeOrphans, Project: project, Timeout: timeout, Images: opts.images, Volumes: opts.volumes, Services: services, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/config.go
cmd/compose/config.go
/* 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 ( "bytes" "context" "encoding/json" "fmt" "io" "os" "sort" "strings" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/template" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "go.yaml.in/yaml/v4" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type configOptions struct { *ProjectOptions Format string Output string quiet bool resolveImageDigests bool noInterpolate bool noNormalize bool noResolvePath bool noResolveEnv bool services bool volumes bool networks bool models bool profiles bool images bool hash string noConsistency bool variables bool environment bool lockImageDigests bool } func (o *configOptions) ToProject(ctx context.Context, dockerCli command.Cli, backend api.Compose, services []string) (*types.Project, error) { project, _, err := o.ProjectOptions.ToProject(ctx, dockerCli, backend, services, o.toProjectOptionsFns()...) return project, err } func (o *configOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) { po = append(po, o.toProjectOptionsFns()...) return o.ProjectOptions.ToModel(ctx, dockerCli, services, po...) } // toProjectOptionsFns converts config options to cli.ProjectOptionsFn func (o *configOptions) toProjectOptionsFns() []cli.ProjectOptionsFn { fns := []cli.ProjectOptionsFn{ cli.WithInterpolation(!o.noInterpolate), cli.WithResolvedPaths(!o.noResolvePath), cli.WithNormalization(!o.noNormalize), cli.WithConsistency(!o.noConsistency), cli.WithDefaultProfiles(o.Profiles...), cli.WithDiscardEnvFile, } if o.noResolveEnv { fns = append(fns, cli.WithoutEnvironmentResolution) } return fns } func configCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command { opts := configOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "config [OPTIONS] [SERVICE...]", Short: "Parse, resolve and render compose file in canonical format", PreRunE: Adapt(func(ctx context.Context, args []string) error { if opts.quiet { devnull, err := os.Open(os.DevNull) if err != nil { return err } os.Stdout = devnull } if p.Compatibility { opts.noNormalize = true } if opts.lockImageDigests { opts.resolveImageDigests = true } return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { if opts.services { return runServices(ctx, dockerCli, opts) } if opts.volumes { return runVolumes(ctx, dockerCli, opts) } if opts.networks { return runNetworks(ctx, dockerCli, opts) } if opts.models { return runModels(ctx, dockerCli, opts) } if opts.hash != "" { return runHash(ctx, dockerCli, opts) } if opts.profiles { return runProfiles(ctx, dockerCli, opts, args) } if opts.images { return runConfigImages(ctx, dockerCli, opts, args) } if opts.variables { return runVariables(ctx, dockerCli, opts, args) } if opts.environment { return runEnvironment(ctx, dockerCli, opts, args) } if opts.Format == "" { opts.Format = "yaml" } return runConfig(ctx, dockerCli, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.StringVar(&opts.Format, "format", "", "Format the output. Values: [yaml | json]") flags.BoolVar(&opts.resolveImageDigests, "resolve-image-digests", false, "Pin image tags to digests") flags.BoolVar(&opts.lockImageDigests, "lock-image-digests", false, "Produces an override file with image digests") flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only validate the configuration, don't print anything") flags.BoolVar(&opts.noInterpolate, "no-interpolate", false, "Don't interpolate environment variables") flags.BoolVar(&opts.noNormalize, "no-normalize", false, "Don't normalize compose model") flags.BoolVar(&opts.noResolvePath, "no-path-resolution", false, "Don't resolve file paths") flags.BoolVar(&opts.noConsistency, "no-consistency", false, "Don't check model consistency - warning: may produce invalid Compose output") flags.BoolVar(&opts.noResolveEnv, "no-env-resolution", false, "Don't resolve service env files") flags.BoolVar(&opts.services, "services", false, "Print the service names, one per line.") flags.BoolVar(&opts.volumes, "volumes", false, "Print the volume names, one per line.") flags.BoolVar(&opts.networks, "networks", false, "Print the network names, one per line.") flags.BoolVar(&opts.models, "models", false, "Print the model names, one per line.") flags.BoolVar(&opts.profiles, "profiles", false, "Print the profile names, one per line.") flags.BoolVar(&opts.images, "images", false, "Print the image names, one per line.") flags.StringVar(&opts.hash, "hash", "", "Print the service config hash, one per line.") flags.BoolVar(&opts.variables, "variables", false, "Print model variables and default values.") flags.BoolVar(&opts.environment, "environment", false, "Print environment used for interpolation.") flags.StringVarP(&opts.Output, "output", "o", "", "Save to file (default to stdout)") return cmd } func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) (err error) { var content []byte if opts.noInterpolate { content, err = runConfigNoInterpolate(ctx, dockerCli, opts, services) if err != nil { return err } } else { content, err = runConfigInterpolate(ctx, dockerCli, opts, services) if err != nil { return err } } if !opts.noInterpolate { content = escapeDollarSign(content) } if opts.quiet { return nil } if opts.Output != "" && len(content) > 0 { return os.WriteFile(opts.Output, content, 0o666) } _, err = fmt.Fprint(dockerCli.Out(), string(content)) return err } func runConfigInterpolate(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) ([]byte, error) { backend, err := compose.NewComposeService(dockerCli) if err != nil { return nil, err } project, err := opts.ToProject(ctx, dockerCli, backend, services) if err != nil { return nil, err } if opts.resolveImageDigests { project, err = project.WithImagesResolved(compose.ImageDigestResolver(ctx, dockerCli.ConfigFile(), dockerCli.Client())) if err != nil { return nil, err } } if !opts.noResolveEnv { project, err = project.WithServicesEnvironmentResolved(true) if err != nil { return nil, err } } if !opts.noConsistency { err := project.CheckContainerNameUnicity() if err != nil { return nil, err } } if opts.lockImageDigests { project = imagesOnly(project) } var content []byte switch opts.Format { case "json": content, err = project.MarshalJSON() case "yaml": content, err = project.MarshalYAML() default: return nil, fmt.Errorf("unsupported format %q", opts.Format) } if err != nil { return nil, err } return content, nil } // imagesOnly return project with all attributes removed but service.images func imagesOnly(project *types.Project) *types.Project { digests := types.Services{} for name, config := range project.Services { digests[name] = types.ServiceConfig{ Image: config.Image, } } project = &types.Project{Services: digests} return project } func runConfigNoInterpolate(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) ([]byte, error) { // we can't use ToProject, so the model we render here is only partially resolved model, err := opts.ToModel(ctx, dockerCli, services) if err != nil { return nil, err } if opts.resolveImageDigests { err = resolveImageDigests(ctx, dockerCli, model) if err != nil { return nil, err } } if opts.lockImageDigests { for key, e := range model { if key != "services" { delete(model, key) } else { for _, s := range e.(map[string]any) { service := s.(map[string]any) for key := range service { if key != "image" { delete(service, key) } } } } } } return formatModel(model, opts.Format) } func resolveImageDigests(ctx context.Context, dockerCli command.Cli, model map[string]any) (err error) { // create a pseudo-project so we can rely on WithImagesResolved to resolve images p := &types.Project{ Services: types.Services{}, } services := model["services"].(map[string]any) for name, s := range services { service := s.(map[string]any) if image, ok := service["image"]; ok { p.Services[name] = types.ServiceConfig{ Image: image.(string), } } } p, err = p.WithImagesResolved(compose.ImageDigestResolver(ctx, dockerCli.ConfigFile(), dockerCli.Client())) if err != nil { return err } // Collect image resolved with digest and update model accordingly for name, s := range services { service := s.(map[string]any) config := p.Services[name] if config.Image != "" { service["image"] = config.Image } services[name] = service } model["services"] = services return nil } func formatModel(model map[string]any, format string) (content []byte, err error) { switch format { case "json": return json.MarshalIndent(model, "", " ") case "yaml": buf := bytes.NewBuffer([]byte{}) encoder := yaml.NewEncoder(buf) encoder.SetIndent(2) err = encoder.Encode(model) return buf.Bytes(), err default: return nil, fmt.Errorf("unsupported format %q", format) } } func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error { if opts.noInterpolate { // we can't use ToProject, so the model we render here is only partially resolved data, err := opts.ToModel(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } if _, ok := data["services"]; ok { for serviceName := range data["services"].(map[string]any) { _, _ = fmt.Fprintln(dockerCli.Out(), serviceName) } } return nil } backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } err = project.ForEachService(project.ServiceNames(), func(serviceName string, _ *types.ServiceConfig) error { _, _ = fmt.Fprintln(dockerCli.Out(), serviceName) return nil }) return err } func runVolumes(ctx context.Context, dockerCli command.Cli, opts configOptions) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } for n := range project.Volumes { _, _ = fmt.Fprintln(dockerCli.Out(), n) } return nil } func runNetworks(ctx context.Context, dockerCli command.Cli, opts configOptions) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } for n := range project.Networks { _, _ = fmt.Fprintln(dockerCli.Out(), n) } return nil } func runModels(ctx context.Context, dockerCli command.Cli, opts configOptions) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } for _, model := range project.Models { if model.Model != "" { _, _ = fmt.Fprintln(dockerCli.Out(), model.Model) } } return nil } func runHash(ctx context.Context, dockerCli command.Cli, opts configOptions) error { var services []string if opts.hash != "*" { services = append(services, strings.Split(opts.hash, ",")...) } backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, _, err := opts.ProjectOptions.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } if err := applyPlatforms(project, true); err != nil { return err } if len(services) == 0 { services = project.ServiceNames() } sorted := services sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] }) for _, name := range sorted { s, err := project.GetService(name) if err != nil { return err } hash, err := compose.ServiceHash(s) if err != nil { return err } _, _ = fmt.Fprintf(dockerCli.Out(), "%s %s\n", name, hash) } return nil } func runProfiles(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error { set := map[string]struct{}{} backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, err := opts.ToProject(ctx, dockerCli, backend, services) if err != nil { return err } for _, s := range project.AllServices() { for _, p := range s.Profiles { set[p] = struct{}{} } } profiles := make([]string, 0, len(set)) for p := range set { profiles = append(profiles, p) } sort.Strings(profiles) for _, p := range profiles { _, _ = fmt.Fprintln(dockerCli.Out(), p) } return nil } func runConfigImages(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, err := opts.ToProject(ctx, dockerCli, backend, services) if err != nil { return err } for _, s := range project.Services { _, _ = fmt.Fprintln(dockerCli.Out(), api.GetImageNameOrDefault(s, project.Name)) } return nil } func runVariables(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error { opts.noInterpolate = true model, err := opts.ToModel(ctx, dockerCli, services, cli.WithoutEnvironmentResolution) if err != nil { return err } variables := template.ExtractVariables(model, template.DefaultPattern) if opts.Format == "yaml" { result, err := yaml.Marshal(variables) if err != nil { return err } fmt.Print(string(result)) return nil } return formatter.Print(variables, opts.Format, dockerCli.Out(), func(w io.Writer) { for name, variable := range variables { _, _ = fmt.Fprintf(w, "%s\t%t\t%s\t%s\n", name, variable.Required, variable.DefaultValue, variable.PresenceValue) } }, "NAME", "REQUIRED", "DEFAULT VALUE", "ALTERNATE VALUE") } func runEnvironment(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, err := opts.ToProject(ctx, dockerCli, backend, services) if err != nil { return err } for _, v := range project.Environment.Values() { fmt.Println(v) } return nil } func escapeDollarSign(marshal []byte) []byte { dollar := []byte{'$'} escDollar := []byte{'$', '$'} return bytes.ReplaceAll(marshal, dollar, escDollar) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/attach.go
cmd/compose/attach.go
/* 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 ( "context" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type attachOpts struct { *composeOptions service string index int detachKeys string noStdin bool proxy bool } func attachCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := attachOpts{ composeOptions: &composeOptions{ ProjectOptions: p, }, } runCmd := &cobra.Command{ Use: "attach [OPTIONS] SERVICE", Short: "Attach local standard input, output, and error streams to a service's running container", Args: cobra.MinimumNArgs(1), PreRunE: Adapt(func(ctx context.Context, args []string) error { opts.service = args[0] return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { return runAttach(ctx, dockerCli, backendOptions, opts) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } runCmd.Flags().IntVar(&opts.index, "index", 0, "index of the container if service has multiple replicas.") runCmd.Flags().StringVarP(&opts.detachKeys, "detach-keys", "", "", "Override the key sequence for detaching from a container.") runCmd.Flags().BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN") runCmd.Flags().BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process") return runCmd } func runAttach(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts attachOpts) error { projectName, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } attachOpts := api.AttachOptions{ Service: opts.service, Index: opts.index, DetachKeys: opts.detachKeys, NoStdin: opts.noStdin, Proxy: opts.proxy, } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Attach(ctx, projectName, attachOpts) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/build.go
cmd/compose/build.go
/* 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 ( "context" "fmt" "os" "strings" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" cliopts "github.com/docker/cli/opts" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/display" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type buildOptions struct { *ProjectOptions quiet bool pull bool push bool args []string noCache bool memory cliopts.MemBytes ssh string builder string deps bool print bool check bool sbom string provenance string } func (opts buildOptions) toAPIBuildOptions(services []string) (api.BuildOptions, error) { var SSHKeys []types.SSHKey if opts.ssh != "" { id, path, found := strings.Cut(opts.ssh, "=") if !found && id != "default" { return api.BuildOptions{}, fmt.Errorf("invalid ssh key %q", opts.ssh) } SSHKeys = append(SSHKeys, types.SSHKey{ ID: id, Path: path, }) } builderName := opts.builder if builderName == "" { builderName = os.Getenv("BUILDX_BUILDER") } uiMode := display.Mode if uiMode == display.ModeJSON { uiMode = "rawjson" } return api.BuildOptions{ Pull: opts.pull, Push: opts.push, Progress: uiMode, Args: types.NewMappingWithEquals(opts.args), NoCache: opts.noCache, Quiet: opts.quiet, Services: services, Deps: opts.deps, Memory: int64(opts.memory), Print: opts.print, Check: opts.check, SSHs: SSHKeys, Builder: builderName, SBOM: opts.sbom, Provenance: opts.provenance, }, nil } func buildCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := buildOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "build [OPTIONS] [SERVICE...]", Short: "Build or rebuild services", PreRunE: Adapt(func(ctx context.Context, args []string) error { if opts.quiet { display.Mode = display.ModeQuiet devnull, err := os.Open(os.DevNull) if err != nil { return err } os.Stdout = devnull } return nil }), RunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { if cmd.Flags().Changed("ssh") && opts.ssh == "" { opts.ssh = "default" } if cmd.Flags().Changed("progress") && opts.ssh == "" { fmt.Fprint(os.Stderr, "--progress is a global compose flag, better use `docker compose --progress xx build ...\n") } return runBuild(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.BoolVar(&opts.push, "push", false, "Push service images") flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Suppress the build output") flags.BoolVar(&opts.pull, "pull", false, "Always attempt to pull a newer version of the image") flags.StringArrayVar(&opts.args, "build-arg", []string{}, "Set build-time variables for services") flags.StringVar(&opts.ssh, "ssh", "", "Set SSH authentications used when building service images. (use 'default' for using your default SSH Agent)") flags.StringVar(&opts.builder, "builder", "", "Set builder to use") flags.BoolVar(&opts.deps, "with-dependencies", false, "Also build dependencies (transitively)") flags.StringVar(&opts.provenance, "provenance", "", `Add a provenance attestation`) flags.StringVar(&opts.sbom, "sbom", "", `Add a SBOM attestation`) flags.Bool("parallel", true, "Build images in parallel. DEPRECATED") flags.MarkHidden("parallel") //nolint:errcheck flags.Bool("compress", true, "Compress the build context using gzip. DEPRECATED") flags.MarkHidden("compress") //nolint:errcheck flags.Bool("force-rm", true, "Always remove intermediate containers. DEPRECATED") flags.MarkHidden("force-rm") //nolint:errcheck flags.BoolVar(&opts.noCache, "no-cache", false, "Do not use cache when building the image") flags.Bool("no-rm", false, "Do not remove intermediate containers after a successful build. DEPRECATED") flags.MarkHidden("no-rm") //nolint:errcheck flags.VarP(&opts.memory, "memory", "m", "Set memory limit for the build container. Not supported by BuildKit.") flags.StringVar(&p.Progress, "progress", "", fmt.Sprintf(`Set type of ui output (%s)`, strings.Join(printerModes, ", "))) flags.MarkHidden("progress") //nolint:errcheck flags.BoolVar(&opts.print, "print", false, "Print equivalent bake file") flags.BoolVar(&opts.check, "check", false, "Check build configuration") return cmd } func runBuild(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts buildOptions, services []string) error { if opts.print { backendOptions.Add(compose.WithEventProcessor(display.Quiet())) } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } opts.All = true // do not drop resources as build may involve some dependencies by additional_contexts project, _, err := opts.ToProject(ctx, dockerCli, backend, nil, cli.WithoutEnvironmentResolution) if err != nil { return err } if err := applyPlatforms(project, false); err != nil { return err } apiBuildOptions, err := opts.toAPIBuildOptions(services) if err != nil { return err } apiBuildOptions.Attestations = true return backend.Build(ctx, project, apiBuildOptions) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/restart.go
cmd/compose/restart.go
/* 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 ( "context" "time" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type restartOptions struct { *ProjectOptions timeChanged bool timeout int noDeps bool } func restartCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := restartOptions{ ProjectOptions: p, } restartCmd := &cobra.Command{ Use: "restart [OPTIONS] [SERVICE...]", Short: "Restart service containers", PreRun: func(cmd *cobra.Command, args []string) { opts.timeChanged = cmd.Flags().Changed("timeout") }, RunE: Adapt(func(ctx context.Context, args []string) error { return runRestart(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := restartCmd.Flags() flags.IntVarP(&opts.timeout, "timeout", "t", 0, "Specify a shutdown timeout in seconds") flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't restart dependent services") return restartCmd } func runRestart(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts restartOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli) if err != nil { return err } if project != nil && len(services) > 0 { project, err = project.WithServicesEnabled(services...) if err != nil { return err } } var timeout *time.Duration if opts.timeChanged { timeoutValue := time.Duration(opts.timeout) * time.Second timeout = &timeoutValue } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Restart(ctx, name, api.RestartOptions{ Timeout: timeout, Services: services, Project: project, NoDeps: opts.noDeps, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/port.go
cmd/compose/port.go
/* 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 ( "context" "fmt" "strconv" "strings" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type portOptions struct { *ProjectOptions port uint16 protocol string index int } func portCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := portOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "port [OPTIONS] SERVICE PRIVATE_PORT", Short: "Print the public port for a port binding", Args: cobra.MinimumNArgs(2), PreRunE: Adapt(func(ctx context.Context, args []string) error { port, err := strconv.ParseUint(args[1], 10, 16) if err != nil { return err } opts.port = uint16(port) opts.protocol = strings.ToLower(opts.protocol) return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { return runPort(ctx, dockerCli, backendOptions, opts, args[0]) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } cmd.Flags().StringVar(&opts.protocol, "protocol", "tcp", "tcp or udp") cmd.Flags().IntVar(&opts.index, "index", 0, "Index of the container if service has multiple replicas") return cmd } func runPort(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts portOptions, service string) error { projectName, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } ip, port, err := backend.Port(ctx, projectName, service, opts.port, api.PortOptions{ Protocol: opts.protocol, Index: opts.index, }) if err != nil { return err } _, _ = fmt.Fprintf(dockerCli.Out(), "%s:%d\n", ip, port) return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/publish.go
cmd/compose/publish.go
/* 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 ( "context" "errors" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type publishOptions struct { *ProjectOptions resolveImageDigests bool ociVersion string withEnvironment bool assumeYes bool app bool insecureRegistry bool } func publishCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := publishOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "publish [OPTIONS] REPOSITORY[:TAG]", Short: "Publish compose application", RunE: Adapt(func(ctx context.Context, args []string) error { return runPublish(ctx, dockerCli, backendOptions, opts, args[0]) }), Args: cli.ExactArgs(1), } flags := cmd.Flags() flags.BoolVar(&opts.resolveImageDigests, "resolve-image-digests", false, "Pin image tags to digests") flags.StringVar(&opts.ociVersion, "oci-version", "", "OCI image/artifact specification version (automatically determined by default)") flags.BoolVar(&opts.withEnvironment, "with-env", false, "Include environment variables in the published OCI artifact") flags.BoolVarP(&opts.assumeYes, "yes", "y", false, `Assume "yes" as answer to all prompts`) flags.BoolVar(&opts.app, "app", false, "Published compose application (includes referenced images)") flags.BoolVar(&opts.insecureRegistry, "insecure-registry", false, "Use insecure registry") flags.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName { // assumeYes was introduced by mistake as `--y` if name == "y" { logrus.Warn("--y is deprecated, please use --yes instead") name = "yes" } return pflag.NormalizedName(name) }) // Should **only** be used for testing purpose, we don't want to promote use of insecure registries _ = flags.MarkHidden("insecure-registry") return cmd } func runPublish(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts publishOptions, repository string) error { if opts.assumeYes { backendOptions.Options = append(backendOptions.Options, compose.WithPrompt(compose.AlwaysOkPrompt())) } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, metrics, err := opts.ToProject(ctx, dockerCli, backend, nil) if err != nil { return err } if metrics.CountIncludesLocal > 0 { return errors.New("cannot publish compose file with local includes") } return backend.Publish(ctx, project, repository, api.PublishOptions{ ResolveImageDigests: opts.resolveImageDigests || opts.app, Application: opts.app, OCIVersion: api.OCIVersion(opts.ociVersion), WithEnvironment: opts.withEnvironment, InsecureRegistry: opts.insecureRegistry, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/images.go
cmd/compose/images.go
/* 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 ( "context" "fmt" "io" "maps" "slices" "strings" "time" "github.com/containerd/platforms" "github.com/docker/cli/cli/command" "github.com/docker/docker/pkg/stringid" "github.com/docker/go-units" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type imageOptions struct { *ProjectOptions Quiet bool Format string } func imagesCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := imageOptions{ ProjectOptions: p, } imgCmd := &cobra.Command{ Use: "images [OPTIONS] [SERVICE...]", Short: "List images used by the created containers", RunE: Adapt(func(ctx context.Context, args []string) error { return runImages(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } imgCmd.Flags().StringVar(&opts.Format, "format", "table", "Format the output. Values: [table | json]") imgCmd.Flags().BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs") return imgCmd } func runImages(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts imageOptions, services []string) error { projectName, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } images, err := backend.Images(ctx, projectName, api.ImagesOptions{ Services: services, }) if err != nil { return err } if opts.Quiet { ids := []string{} for _, img := range images { id := img.ID if i := strings.IndexRune(img.ID, ':'); i >= 0 { id = id[i+1:] } if !slices.Contains(ids, id) { ids = append(ids, id) } } for _, img := range ids { _, _ = fmt.Fprintln(dockerCli.Out(), img) } return nil } if opts.Format == "json" { type img struct { ID string `json:"ID"` ContainerName string `json:"ContainerName"` Repository string `json:"Repository"` Tag string `json:"Tag"` Platform string `json:"Platform"` Size int64 `json:"Size"` Created *time.Time `json:"Created,omitempty"` LastTagTime time.Time `json:"LastTagTime,omitzero"` } // Convert map to slice var imageList []img for ctr, i := range images { lastTagTime := i.LastTagTime imageList = append(imageList, img{ ContainerName: ctr, ID: i.ID, Repository: i.Repository, Tag: i.Tag, Platform: platforms.Format(i.Platform), Size: i.Size, Created: i.Created, LastTagTime: lastTagTime, }) } json, err := formatter.ToJSON(imageList, "", "") if err != nil { return err } _, err = fmt.Fprintln(dockerCli.Out(), json) return err } return formatter.Print(images, opts.Format, dockerCli.Out(), func(w io.Writer) { for _, container := range slices.Sorted(maps.Keys(images)) { img := images[container] id := stringid.TruncateID(img.ID) size := units.HumanSizeWithPrecision(float64(img.Size), 3) repo := img.Repository if repo == "" { repo = "<none>" } tag := img.Tag if tag == "" { tag = "<none>" } created := "N/A" if img.Created != nil { created = units.HumanDuration(time.Now().UTC().Sub(*img.Created)) + " ago" } _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", container, repo, tag, platforms.Format(img.Platform), id, size, created) } }, "CONTAINER", "REPOSITORY", "TAG", "PLATFORM", "IMAGE ID", "SIZE", "CREATED") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/top.go
cmd/compose/top.go
/* 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 ( "context" "fmt" "io" "sort" "strings" "text/tabwriter" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type topOptions struct { *ProjectOptions } func topCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := topOptions{ ProjectOptions: p, } topCmd := &cobra.Command{ Use: "top [SERVICES...]", Short: "Display the running processes", RunE: Adapt(func(ctx context.Context, args []string) error { return runTop(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } return topCmd } type ( topHeader map[string]int // maps a proc title to its output index topEntries map[string]string ) func runTop(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts topOptions, services []string) error { projectName, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } containers, err := backend.Top(ctx, projectName, services) if err != nil { return err } sort.Slice(containers, func(i, j int) bool { return containers[i].Name < containers[j].Name }) header, entries := collectTop(containers) return topPrint(dockerCli.Out(), header, entries) } func collectTop(containers []api.ContainerProcSummary) (topHeader, []topEntries) { // map column name to its header (should keep working if backend.Top returns // varying columns for different containers) header := topHeader{"SERVICE": 0, "#": 1} // assume one process per container and grow if needed entries := make([]topEntries, 0, len(containers)) for _, container := range containers { for _, proc := range container.Processes { entry := topEntries{ "SERVICE": container.Service, "#": container.Replica, } for i, title := range container.Titles { if _, exists := header[title]; !exists { header[title] = len(header) } entry[title] = proc[i] } entries = append(entries, entry) } } // ensure CMD is the right-most column if pos, ok := header["CMD"]; ok { maxPos := pos for h, i := range header { if i > maxPos { maxPos = i } if i > pos { header[h] = i - 1 } } header["CMD"] = maxPos } return header, entries } func topPrint(out io.Writer, headers topHeader, rows []topEntries) error { if len(rows) == 0 { return nil } w := tabwriter.NewWriter(out, 4, 1, 2, ' ', 0) // write headers in the order we've encountered them h := make([]string, len(headers)) for title, index := range headers { h[index] = title } _, _ = fmt.Fprintln(w, strings.Join(h, "\t")) for _, row := range rows { // write proc data in header order r := make([]string, len(headers)) for title, index := range headers { if v, ok := row[title]; ok { r[index] = v } else { r[index] = "-" } } _, _ = fmt.Fprintln(w, strings.Join(r, "\t")) } return w.Flush() }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/watch.go
cmd/compose/watch.go
/* 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 ( "context" "fmt" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/internal/locker" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type watchOptions struct { *ProjectOptions prune bool noUp bool } func watchCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { watchOpts := watchOptions{ ProjectOptions: p, } buildOpts := buildOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "watch [SERVICE...]", Short: "Watch build context for service and rebuild/refresh containers when files are updated", PreRunE: Adapt(func(ctx context.Context, args []string) error { return nil }), RunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { if cmd.Parent().Name() == "alpha" { logrus.Warn("watch command is now available as a top level command") } return runWatch(ctx, dockerCli, backendOptions, watchOpts, buildOpts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } cmd.Flags().BoolVar(&buildOpts.quiet, "quiet", false, "hide build output") cmd.Flags().BoolVar(&watchOpts.prune, "prune", true, "Prune dangling images on rebuild") cmd.Flags().BoolVar(&watchOpts.noUp, "no-up", false, "Do not build & start services before watching") return cmd } func runWatch(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, watchOpts watchOptions, buildOpts buildOptions, services []string) error { backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, _, err := watchOpts.ToProject(ctx, dockerCli, backend, services) if err != nil { return err } if err := applyPlatforms(project, true); err != nil { return err } build, err := buildOpts.toAPIBuildOptions(nil) if err != nil { return err } // validation done -- ensure we have the lockfile for this project before doing work l, err := locker.NewPidfile(project.Name) if err != nil { return fmt.Errorf("cannot take exclusive lock for project %q: %w", project.Name, err) } if err := l.Lock(); err != nil { return fmt.Errorf("cannot take exclusive lock for project %q: %w", project.Name, err) } if !watchOpts.noUp { for index, service := range project.Services { if service.Build != nil && service.Develop != nil { service.PullPolicy = types.PullPolicyBuild } project.Services[index] = service } upOpts := api.UpOptions{ Create: api.CreateOptions{ Build: &build, Services: services, RemoveOrphans: false, Recreate: api.RecreateDiverged, RecreateDependencies: api.RecreateNever, Inherit: true, QuietPull: buildOpts.quiet, }, Start: api.StartOptions{ Project: project, Attach: nil, Services: services, }, } if err := backend.Up(ctx, project, upOpts); err != nil { return err } } consumer := formatter.NewLogConsumer(ctx, dockerCli.Out(), dockerCli.Err(), false, false, false) return backend.Watch(ctx, project, api.WatchOptions{ Build: &build, LogTo: consumer, Prune: watchOpts.prune, Services: services, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/ps.go
cmd/compose/ps.go
/* 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 ( "context" "errors" "fmt" "slices" "sort" "strings" "github.com/docker/cli/cli/command" cliformatter "github.com/docker/cli/cli/command/formatter" cliflags "github.com/docker/cli/cli/flags" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type psOptions struct { *ProjectOptions Format string All bool Quiet bool Services bool Filter string Status []string noTrunc bool Orphans bool } func (p *psOptions) parseFilter() error { if p.Filter == "" { return nil } parts := strings.SplitN(p.Filter, "=", 2) if len(parts) != 2 { return errors.New("arguments to --filter should be in form KEY=VAL") } switch parts[0] { case "status": p.Status = append(p.Status, parts[1]) case "source": return api.ErrNotImplemented default: return fmt.Errorf("unknown filter %s", parts[0]) } return nil } func psCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := psOptions{ ProjectOptions: p, } psCmd := &cobra.Command{ Use: "ps [OPTIONS] [SERVICE...]", Short: "List containers", PreRunE: func(cmd *cobra.Command, args []string) error { return opts.parseFilter() }, RunE: Adapt(func(ctx context.Context, args []string) error { return runPs(ctx, dockerCli, backendOptions, args, opts) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := psCmd.Flags() flags.StringVar(&opts.Format, "format", "table", cliflags.FormatHelp) flags.StringVar(&opts.Filter, "filter", "", "Filter services by a property (supported filters: status)") flags.StringArrayVar(&opts.Status, "status", []string{}, "Filter services by status. Values: [paused | restarting | removing | running | dead | created | exited]") flags.BoolVarP(&opts.Quiet, "quiet", "q", false, "Only display IDs") flags.BoolVar(&opts.Services, "services", false, "Display services") flags.BoolVar(&opts.Orphans, "orphans", true, "Include orphaned services (not declared by project)") flags.BoolVarP(&opts.All, "all", "a", false, "Show all stopped containers (including those created by the run command)") flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output") return psCmd } func runPs(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, services []string, opts psOptions) error { //nolint:gocyclo project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } if project != nil { names := project.ServiceNames() if len(services) > 0 { for _, service := range services { if !slices.Contains(names, service) { return fmt.Errorf("no such service: %s", service) } } } else if !opts.Orphans { // until user asks to list orphaned services, we only include those declared in project services = names } } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } containers, err := backend.Ps(ctx, name, api.PsOptions{ Project: project, All: opts.All || len(opts.Status) != 0, Services: services, }) if err != nil { return err } if len(opts.Status) != 0 { containers = filterByStatus(containers, opts.Status) } sort.Slice(containers, func(i, j int) bool { return containers[i].Name < containers[j].Name }) if opts.Quiet { for _, c := range containers { _, _ = fmt.Fprintln(dockerCli.Out(), c.ID) } return nil } if opts.Services { services := []string{} for _, c := range containers { s := c.Service if !slices.Contains(services, s) { services = append(services, s) } } _, _ = fmt.Fprintln(dockerCli.Out(), strings.Join(services, "\n")) return nil } if opts.Format == "" { opts.Format = dockerCli.ConfigFile().PsFormat } containerCtx := cliformatter.Context{ Output: dockerCli.Out(), Format: formatter.NewContainerFormat(opts.Format, opts.Quiet, false), Trunc: !opts.noTrunc, } return formatter.ContainerWrite(containerCtx, containers) } func filterByStatus(containers []api.ContainerSummary, statuses []string) []api.ContainerSummary { var filtered []api.ContainerSummary for _, c := range containers { if hasStatus(c, statuses) { filtered = append(filtered, c) } } return filtered } func hasStatus(c api.ContainerSummary, statuses []string) bool { for _, status := range statuses { if c.State == status { return true } } return false }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/list.go
cmd/compose/list.go
/* 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 ( "context" "fmt" "io" "strings" "github.com/docker/cli/cli/command" "github.com/docker/cli/opts" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type lsOptions struct { Format string Quiet bool All bool Filter opts.FilterOpt } func listCommand(dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { lsOpts := lsOptions{Filter: opts.NewFilterOpt()} lsCmd := &cobra.Command{ Use: "ls [OPTIONS]", Short: "List running compose projects", RunE: Adapt(func(ctx context.Context, args []string) error { return runList(ctx, dockerCli, backendOptions, lsOpts) }), Args: cobra.NoArgs, ValidArgsFunction: noCompletion(), } lsCmd.Flags().StringVar(&lsOpts.Format, "format", "table", "Format the output. Values: [table | json]") lsCmd.Flags().BoolVarP(&lsOpts.Quiet, "quiet", "q", false, "Only display project names") lsCmd.Flags().Var(&lsOpts.Filter, "filter", "Filter output based on conditions provided") lsCmd.Flags().BoolVarP(&lsOpts.All, "all", "a", false, "Show all stopped Compose projects") return lsCmd } var acceptedListFilters = map[string]bool{ "name": true, } func runList(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, lsOpts lsOptions) error { filters := lsOpts.Filter.Value() err := filters.Validate(acceptedListFilters) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } stackList, err := backend.List(ctx, api.ListOptions{All: lsOpts.All}) if err != nil { return err } if filters.Len() > 0 { var filtered []api.Stack for _, s := range stackList { if filters.Contains("name") && !filters.Match("name", s.Name) { continue } filtered = append(filtered, s) } stackList = filtered } if lsOpts.Quiet { for _, s := range stackList { _, _ = fmt.Fprintln(dockerCli.Out(), s.Name) } return nil } view := viewFromStackList(stackList) return formatter.Print(view, lsOpts.Format, dockerCli.Out(), func(w io.Writer) { for _, stack := range view { _, _ = fmt.Fprintf(w, "%s\t%s\t%s\n", stack.Name, stack.Status, stack.ConfigFiles) } }, "NAME", "STATUS", "CONFIG FILES") } type stackView struct { Name string Status string ConfigFiles string } func viewFromStackList(stackList []api.Stack) []stackView { retList := make([]stackView, len(stackList)) for i, s := range stackList { retList[i] = stackView{ Name: s.Name, Status: strings.TrimSpace(fmt.Sprintf("%s %s", s.Status, s.Reason)), ConfigFiles: s.ConfigFiles, } } return retList }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/version_test.go
cmd/compose/version_test.go
/* Copyright 2025 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 ( "bytes" "testing" "github.com/docker/cli/cli/streams" "go.uber.org/mock/gomock" "gotest.tools/v3/assert" "github.com/docker/compose/v5/internal" "github.com/docker/compose/v5/pkg/mocks" ) func TestVersionCommand(t *testing.T) { originalVersion := internal.Version defer func() { internal.Version = originalVersion }() internal.Version = "v9.9.9-test" tests := []struct { name string args []string want string }{ { name: "default", args: []string{}, want: "Docker Compose version v9.9.9-test\n", }, { name: "short flag", args: []string{"--short"}, want: "9.9.9-test\n", }, { name: "json flag", args: []string{"--format", "json"}, want: `{"version":"v9.9.9-test"}` + "\n", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() buf := new(bytes.Buffer) cli := mocks.NewMockCli(ctrl) cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes() cmd := versionCommand(cli) cmd.SetArgs(test.args) err := cmd.Execute() assert.NilError(t, err) assert.Equal(t, test.want, buf.String()) }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/bridge.go
cmd/compose/bridge.go
/* 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 ( "context" "fmt" "io" "github.com/distribution/reference" "github.com/docker/cli/cli/command" "github.com/docker/docker/api/types/image" "github.com/docker/docker/pkg/stringid" "github.com/docker/go-units" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/bridge" "github.com/docker/compose/v5/pkg/compose" ) func bridgeCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "bridge CMD [OPTIONS]", Short: "Convert compose files into another model", TraverseChildren: true, } cmd.AddCommand( convertCommand(p, dockerCli), transformersCommand(dockerCli), ) return cmd } func convertCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command { convertOpts := bridge.ConvertOptions{} cmd := &cobra.Command{ Use: "convert", Short: "Convert compose files to Kubernetes manifests, Helm charts, or another model", RunE: Adapt(func(ctx context.Context, args []string) error { return runConvert(ctx, dockerCli, p, convertOpts) }), } flags := cmd.Flags() flags.StringVarP(&convertOpts.Output, "output", "o", "out", "The output directory for the Kubernetes resources") flags.StringArrayVarP(&convertOpts.Transformations, "transformation", "t", nil, "Transformation to apply to compose model (default: docker/compose-bridge-kubernetes)") flags.StringVar(&convertOpts.Templates, "templates", "", "Directory containing transformation templates") return cmd } func runConvert(ctx context.Context, dockerCli command.Cli, p *ProjectOptions, opts bridge.ConvertOptions) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, _, err := p.ToProject(ctx, dockerCli, backend, nil) if err != nil { return err } return bridge.Convert(ctx, dockerCli, project, opts) } func transformersCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "transformations CMD [OPTIONS]", Short: "Manage transformation images", } cmd.AddCommand( listTransformersCommand(dockerCli), createTransformerCommand(dockerCli), ) return cmd } func listTransformersCommand(dockerCli command.Cli) *cobra.Command { options := lsOptions{} cmd := &cobra.Command{ Use: "list", Aliases: []string{"ls"}, Short: "List available transformations", RunE: Adapt(func(ctx context.Context, args []string) error { transformers, err := bridge.ListTransformers(ctx, dockerCli) if err != nil { return err } return displayTransformer(dockerCli, transformers, options) }), } cmd.Flags().StringVar(&options.Format, "format", "table", "Format the output. Values: [table | json]") cmd.Flags().BoolVarP(&options.Quiet, "quiet", "q", false, "Only display transformer names") return cmd } func displayTransformer(dockerCli command.Cli, transformers []image.Summary, options lsOptions) error { if options.Quiet { for _, t := range transformers { if len(t.RepoTags) > 0 { _, _ = fmt.Fprintln(dockerCli.Out(), t.RepoTags[0]) } else { _, _ = fmt.Fprintln(dockerCli.Out(), t.ID) } } return nil } return formatter.Print(transformers, options.Format, dockerCli.Out(), func(w io.Writer) { for _, img := range transformers { id := stringid.TruncateID(img.ID) size := units.HumanSizeWithPrecision(float64(img.Size), 3) repo, tag := "<none>", "<none>" if len(img.RepoTags) > 0 { ref, err := reference.ParseDockerRef(img.RepoTags[0]) if err == nil { // ParseDockerRef will reject a local image ID repo = reference.FamiliarName(ref) if tagged, ok := ref.(reference.Tagged); ok { tag = tagged.Tag() } } } _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", id, repo, tag, size) } }, "IMAGE ID", "REPO", "TAGS", "SIZE") } func createTransformerCommand(dockerCli command.Cli) *cobra.Command { var opts bridge.CreateTransformerOptions cmd := &cobra.Command{ Use: "create [OPTION] PATH", Short: "Create a new transformation", RunE: Adapt(func(ctx context.Context, args []string) error { opts.Dest = args[0] return bridge.CreateTransformer(ctx, dockerCli, opts) }), } cmd.Flags().StringVarP(&opts.From, "from", "f", "", "Existing transformation to copy (default: docker/compose-bridge-kubernetes)") return cmd }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/options_test.go
cmd/compose/options_test.go
/* Copyright 2023 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 ( "bytes" "context" "fmt" "io" "os" "path/filepath" "strings" "testing" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/streams" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "github.com/docker/compose/v5/pkg/mocks" ) func TestApplyPlatforms_InferFromRuntime(t *testing.T) { makeProject := func() *types.Project { return &types.Project{ Services: types.Services{ "test": { Name: "test", Image: "foo", Build: &types.BuildConfig{ Context: ".", Platforms: []string{ "linux/amd64", "linux/arm64", "alice/32", }, }, Platform: "alice/32", }, }, } } t.Run("SinglePlatform", func(t *testing.T) { project := makeProject() require.NoError(t, applyPlatforms(project, true)) require.EqualValues(t, []string{"alice/32"}, project.Services["test"].Build.Platforms) }) t.Run("MultiPlatform", func(t *testing.T) { project := makeProject() require.NoError(t, applyPlatforms(project, false)) require.EqualValues(t, []string{"linux/amd64", "linux/arm64", "alice/32"}, project.Services["test"].Build.Platforms) }) } func TestApplyPlatforms_DockerDefaultPlatform(t *testing.T) { makeProject := func() *types.Project { return &types.Project{ Environment: map[string]string{ "DOCKER_DEFAULT_PLATFORM": "linux/amd64", }, Services: types.Services{ "test": { Name: "test", Image: "foo", Build: &types.BuildConfig{ Context: ".", Platforms: []string{ "linux/amd64", "linux/arm64", }, }, }, }, } } t.Run("SinglePlatform", func(t *testing.T) { project := makeProject() require.NoError(t, applyPlatforms(project, true)) require.EqualValues(t, []string{"linux/amd64"}, project.Services["test"].Build.Platforms) }) t.Run("MultiPlatform", func(t *testing.T) { project := makeProject() require.NoError(t, applyPlatforms(project, false)) require.EqualValues(t, []string{"linux/amd64", "linux/arm64"}, project.Services["test"].Build.Platforms) }) } func TestApplyPlatforms_UnsupportedPlatform(t *testing.T) { makeProject := func() *types.Project { return &types.Project{ Environment: map[string]string{ "DOCKER_DEFAULT_PLATFORM": "commodore/64", }, Services: types.Services{ "test": { Name: "test", Image: "foo", Build: &types.BuildConfig{ Context: ".", Platforms: []string{ "linux/amd64", "linux/arm64", }, }, }, }, } } t.Run("SinglePlatform", func(t *testing.T) { project := makeProject() require.EqualError(t, applyPlatforms(project, true), `service "test" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: commodore/64`) }) t.Run("MultiPlatform", func(t *testing.T) { project := makeProject() require.EqualError(t, applyPlatforms(project, false), `service "test" build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: commodore/64`) }) } func TestIsRemoteConfig(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() cli := mocks.NewMockCli(ctrl) tests := []struct { name string configPaths []string want bool }{ { name: "empty config paths", configPaths: []string{}, want: false, }, { name: "local file", configPaths: []string{"docker-compose.yaml"}, want: false, }, { name: "OCI reference", configPaths: []string{"oci://registry.example.com/stack:latest"}, want: true, }, { name: "GIT reference", configPaths: []string{"git://github.com/user/repo.git"}, want: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { opts := buildOptions{ ProjectOptions: &ProjectOptions{ ConfigPaths: tt.configPaths, }, } got := isRemoteConfig(cli, opts) require.Equal(t, tt.want, got) }) } } func TestDisplayLocationRemoteStack(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() cli := mocks.NewMockCli(ctrl) buf := new(bytes.Buffer) cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes() project := &types.Project{ Name: "test-project", WorkingDir: "/tmp/test", } options := buildOptions{ ProjectOptions: &ProjectOptions{ ConfigPaths: []string{"oci://registry.example.com/stack:latest"}, }, } displayLocationRemoteStack(cli, project, options) output := buf.String() require.Equal(t, output, fmt.Sprintf("Your compose stack %q is stored in %q\n", "oci://registry.example.com/stack:latest", "/tmp/test")) } func TestDisplayInterpolationVariables(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() // Create a temporary directory for the test tmpDir, err := os.MkdirTemp("", "compose-test") require.NoError(t, err) defer func() { _ = os.RemoveAll(tmpDir) }() // Create a temporary compose file composeContent := ` services: app: image: nginx environment: - TEST_VAR=${TEST_VAR:?required} # required with default - API_KEY=${API_KEY:?} # required without default - DEBUG=${DEBUG:-true} # optional with default - UNSET_VAR # optional without default ` composePath := filepath.Join(tmpDir, "docker-compose.yml") err = os.WriteFile(composePath, []byte(composeContent), 0o644) require.NoError(t, err) buf := new(bytes.Buffer) cli := mocks.NewMockCli(ctrl) cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes() // Create ProjectOptions with the temporary compose file projectOptions := &ProjectOptions{ ConfigPaths: []string{composePath}, } // Set up the context with necessary environment variables ctx := context.Background() _ = os.Setenv("TEST_VAR", "test-value") _ = os.Setenv("API_KEY", "123456") defer func() { _ = os.Unsetenv("TEST_VAR") _ = os.Unsetenv("API_KEY") }() // Extract variables from the model info, noVariables, err := extractInterpolationVariablesFromModel(ctx, cli, projectOptions, []string{}) require.NoError(t, err) require.False(t, noVariables) // Display the variables displayInterpolationVariables(cli.Out(), info) // Expected output format with proper spacing expected := "\nFound the following variables in configuration:\n" + "VARIABLE VALUE SOURCE REQUIRED DEFAULT\n" + "API_KEY 123456 environment yes \n" + "DEBUG true compose file no true\n" + "TEST_VAR test-value environment yes \n" // Normalize spaces and newlines for comparison normalizeSpaces := func(s string) string { // Replace multiple spaces with a single space s = strings.Join(strings.Fields(strings.TrimSpace(s)), " ") return s } actualOutput := buf.String() // Compare normalized strings require.Equal(t, normalizeSpaces(expected), normalizeSpaces(actualOutput), "\nExpected:\n%s\nGot:\n%s", expected, actualOutput) } func TestConfirmRemoteIncludes(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() cli := mocks.NewMockCli(ctrl) tests := []struct { name string opts buildOptions assumeYes bool userInput string wantErr bool errMessage string wantPrompt bool wantOutput string }{ { name: "no remote includes", opts: buildOptions{ ProjectOptions: &ProjectOptions{ ConfigPaths: []string{ "docker-compose.yaml", "./local/path/compose.yaml", }, }, }, assumeYes: false, wantErr: false, wantPrompt: false, }, { name: "assume yes with remote includes", opts: buildOptions{ ProjectOptions: &ProjectOptions{ ConfigPaths: []string{ "oci://registry.example.com/stack:latest", "git://github.com/user/repo.git", }, }, }, assumeYes: true, wantErr: false, wantPrompt: false, }, { name: "user confirms remote includes", opts: buildOptions{ ProjectOptions: &ProjectOptions{ ConfigPaths: []string{ "oci://registry.example.com/stack:latest", "git://github.com/user/repo.git", }, }, }, assumeYes: false, userInput: "y\n", wantErr: false, wantPrompt: true, wantOutput: "\nWarning: This Compose project includes files from remote sources:\n" + " - oci://registry.example.com/stack:latest\n" + " - git://github.com/user/repo.git\n" + "\nRemote includes could potentially be malicious. Make sure you trust the source.\n" + "Do you want to continue? [y/N]: ", }, { name: "user rejects remote includes", opts: buildOptions{ ProjectOptions: &ProjectOptions{ ConfigPaths: []string{ "oci://registry.example.com/stack:latest", }, }, }, assumeYes: false, userInput: "n\n", wantErr: true, errMessage: "operation cancelled by user", wantPrompt: true, wantOutput: "\nWarning: This Compose project includes files from remote sources:\n" + " - oci://registry.example.com/stack:latest\n" + "\nRemote includes could potentially be malicious. Make sure you trust the source.\n" + "Do you want to continue? [y/N]: ", }, } buf := new(bytes.Buffer) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { cli.EXPECT().Out().Return(streams.NewOut(buf)).AnyTimes() if tt.wantPrompt { inbuf := io.NopCloser(bytes.NewBufferString(tt.userInput)) cli.EXPECT().In().Return(streams.NewIn(inbuf)).AnyTimes() } err := confirmRemoteIncludes(cli, tt.opts, tt.assumeYes) if tt.wantErr { require.Error(t, err) require.Equal(t, tt.errMessage, err.Error()) } else { require.NoError(t, err) } if tt.wantOutput != "" { require.Equal(t, tt.wantOutput, buf.String()) } buf.Reset() }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/compose.go
cmd/compose/compose.go
/* 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 ( "context" "encoding/json" "errors" "fmt" "io" "os" "os/signal" "path/filepath" "strconv" "strings" "syscall" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/dotenv" "github.com/compose-spec/compose-go/v2/loader" "github.com/compose-spec/compose-go/v2/types" composegoutils "github.com/compose-spec/compose-go/v2/utils" "github.com/docker/buildx/util/logutil" dockercli "github.com/docker/cli/cli" "github.com/docker/cli/cli-plugins/metadata" "github.com/docker/cli/cli/command" "github.com/docker/cli/pkg/kvfile" "github.com/morikuni/aec" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/cmd/display" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/internal/tracing" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" "github.com/docker/compose/v5/pkg/remote" "github.com/docker/compose/v5/pkg/utils" ) const ( // ComposeParallelLimit set the limit running concurrent operation on docker engine ComposeParallelLimit = "COMPOSE_PARALLEL_LIMIT" // ComposeProjectName define the project name to be used, instead of guessing from parent directory ComposeProjectName = "COMPOSE_PROJECT_NAME" // ComposeCompatibility try to mimic compose v1 as much as possible ComposeCompatibility = api.ComposeCompatibility // ComposeRemoveOrphans remove "orphaned" containers, i.e. containers tagged for current project but not declared as service ComposeRemoveOrphans = "COMPOSE_REMOVE_ORPHANS" // ComposeIgnoreOrphans ignore "orphaned" containers ComposeIgnoreOrphans = "COMPOSE_IGNORE_ORPHANS" // ComposeEnvFiles defines the env files to use if --env-file isn't used ComposeEnvFiles = "COMPOSE_ENV_FILES" // ComposeMenu defines if the navigation menu should be rendered. Can be also set via --menu ComposeMenu = "COMPOSE_MENU" // ComposeProgress defines type of progress output, if --progress isn't used ComposeProgress = "COMPOSE_PROGRESS" ) // rawEnv load a dot env file using docker/cli key=value parser, without attempt to interpolate or evaluate values func rawEnv(r io.Reader, filename string, vars map[string]string, lookup func(key string) (string, bool)) error { lines, err := kvfile.ParseFromReader(r, lookup) if err != nil { return fmt.Errorf("failed to parse env_file %s: %w", filename, err) } for _, line := range lines { key, value, _ := strings.Cut(line, "=") vars[key] = value } return nil } var stdioToStdout bool func init() { // compose evaluates env file values for interpolation // `raw` format allows to load env_file with the same parser used by docker run --env-file dotenv.RegisterFormat("raw", rawEnv) if v, ok := os.LookupEnv("COMPOSE_STATUS_STDOUT"); ok { stdioToStdout, _ = strconv.ParseBool(v) } } // Command defines a compose CLI command as a func with args type Command func(context.Context, []string) error // CobraCommand defines a cobra command function type CobraCommand func(context.Context, *cobra.Command, []string) error // AdaptCmd adapt a CobraCommand func to cobra library func AdaptCmd(fn CobraCommand) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { ctx, cancel := context.WithCancel(cmd.Context()) s := make(chan os.Signal, 1) signal.Notify(s, syscall.SIGTERM, syscall.SIGINT) go func() { <-s cancel() signal.Stop(s) close(s) }() err := fn(ctx, cmd, args) if api.IsErrCanceled(err) || errors.Is(ctx.Err(), context.Canceled) { err = dockercli.StatusError{ StatusCode: 130, } } if display.Mode == display.ModeJSON { err = makeJSONError(err) } return err } } // Adapt a Command func to cobra library func Adapt(fn Command) func(cmd *cobra.Command, args []string) error { return AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { return fn(ctx, args) }) } type ProjectOptions struct { ProjectName string Profiles []string ConfigPaths []string WorkDir string ProjectDir string EnvFiles []string Compatibility bool Progress string Offline bool All bool insecureRegistries []string } // ProjectFunc does stuff within a types.Project type ProjectFunc func(ctx context.Context, project *types.Project) error // ProjectServicesFunc does stuff within a types.Project and a selection of services type ProjectServicesFunc func(ctx context.Context, project *types.Project, services []string) error // WithProject creates a cobra run command from a ProjectFunc based on configured project options and selected services func (o *ProjectOptions) WithProject(fn ProjectFunc, dockerCli command.Cli) func(cmd *cobra.Command, args []string) error { return o.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error { return fn(ctx, project) }) } // WithServices creates a cobra run command from a ProjectFunc based on configured project options and selected services func (o *ProjectOptions) WithServices(dockerCli command.Cli, fn ProjectServicesFunc) func(cmd *cobra.Command, args []string) error { return Adapt(func(ctx context.Context, services []string) error { backend, err := compose.NewComposeService(dockerCli) if err != nil { return err } project, metrics, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithoutEnvironmentResolution) if err != nil { return err } ctx = context.WithValue(ctx, tracing.MetricsKey{}, metrics) project, err = project.WithServicesEnvironmentResolved(true) if err != nil { return err } return fn(ctx, project, services) }) } type jsonErrorData struct { Error bool `json:"error,omitempty"` Message string `json:"message,omitempty"` } func errorAsJSON(message string) string { errorMessage := &jsonErrorData{ Error: true, Message: message, } marshal, err := json.Marshal(errorMessage) if err == nil { return string(marshal) } else { return message } } func makeJSONError(err error) error { if err == nil { return nil } var statusErr dockercli.StatusError if errors.As(err, &statusErr) { return dockercli.StatusError{ StatusCode: statusErr.StatusCode, Status: errorAsJSON(statusErr.Status), } } return fmt.Errorf("%s", errorAsJSON(err.Error())) } func (o *ProjectOptions) addProjectFlags(f *pflag.FlagSet) { f.StringArrayVar(&o.Profiles, "profile", []string{}, "Specify a profile to enable") f.StringVarP(&o.ProjectName, "project-name", "p", "", "Project name") f.StringArrayVarP(&o.ConfigPaths, "file", "f", []string{}, "Compose configuration files") f.StringArrayVar(&o.insecureRegistries, "insecure-registry", []string{}, "Use insecure registry to pull Compose OCI artifacts. Doesn't apply to images") _ = f.MarkHidden("insecure-registry") f.StringArrayVar(&o.EnvFiles, "env-file", defaultStringArrayVar(ComposeEnvFiles), "Specify an alternate environment file") f.StringVar(&o.ProjectDir, "project-directory", "", "Specify an alternate working directory\n(default: the path of the, first specified, Compose file)") f.StringVar(&o.WorkDir, "workdir", "", "DEPRECATED! USE --project-directory INSTEAD.\nSpecify an alternate working directory\n(default: the path of the, first specified, Compose file)") f.BoolVar(&o.Compatibility, "compatibility", false, "Run compose in backward compatibility mode") f.StringVar(&o.Progress, "progress", os.Getenv(ComposeProgress), fmt.Sprintf(`Set type of progress output (%s)`, strings.Join(printerModes, ", "))) f.BoolVar(&o.All, "all-resources", false, "Include all resources, even those not used by services") _ = f.MarkHidden("workdir") } // get default value for a command line flag that is set by a coma-separated value in environment variable func defaultStringArrayVar(env string) []string { return strings.FieldsFunc(os.Getenv(env), func(c rune) bool { return c == ',' }) } func (o *ProjectOptions) projectOrName(ctx context.Context, dockerCli command.Cli, services ...string) (*types.Project, string, error) { name := o.ProjectName var project *types.Project if len(o.ConfigPaths) > 0 || o.ProjectName == "" { backend, err := compose.NewComposeService(dockerCli) if err != nil { return nil, "", err } p, _, err := o.ToProject(ctx, dockerCli, backend, services, cli.WithDiscardEnvFile, cli.WithoutEnvironmentResolution) if err != nil { envProjectName := os.Getenv(ComposeProjectName) if envProjectName != "" { return nil, envProjectName, nil } return nil, "", err } project = p name = p.Name } return project, name, nil } func (o *ProjectOptions) toProjectName(ctx context.Context, dockerCli command.Cli) (string, error) { if o.ProjectName != "" { return o.ProjectName, nil } envProjectName := os.Getenv(ComposeProjectName) if envProjectName != "" { return envProjectName, nil } backend, err := compose.NewComposeService(dockerCli) if err != nil { return "", err } project, _, err := o.ToProject(ctx, dockerCli, backend, nil) if err != nil { return "", err } return project.Name, nil } func (o *ProjectOptions) ToModel(ctx context.Context, dockerCli command.Cli, services []string, po ...cli.ProjectOptionsFn) (map[string]any, error) { remotes := o.remoteLoaders(dockerCli) for _, r := range remotes { po = append(po, cli.WithResourceLoader(r)) } options, err := o.toProjectOptions(po...) if err != nil { return nil, err } if o.Compatibility || utils.StringToBool(options.Environment[ComposeCompatibility]) { api.Separator = "_" } return options.LoadModel(ctx) } // ToProject loads a Compose project using the LoadProject API. // Accepts optional cli.ProjectOptionsFn to control loader behavior. func (o *ProjectOptions) ToProject(ctx context.Context, dockerCli command.Cli, backend api.Compose, services []string, po ...cli.ProjectOptionsFn) (*types.Project, tracing.Metrics, error) { var metrics tracing.Metrics remotes := o.remoteLoaders(dockerCli) // Setup metrics listener to collect project data metricsListener := func(event string, metadata map[string]any) { switch event { case "extends": metrics.CountExtends++ case "include": paths := metadata["path"].(types.StringList) for _, path := range paths { var isRemote bool for _, r := range remotes { if r.Accept(path) { isRemote = true break } } if isRemote { metrics.CountIncludesRemote++ } else { metrics.CountIncludesLocal++ } } } } loadOpts := api.ProjectLoadOptions{ ProjectName: o.ProjectName, ConfigPaths: o.ConfigPaths, WorkingDir: o.ProjectDir, EnvFiles: o.EnvFiles, Profiles: o.Profiles, Services: services, Offline: o.Offline, All: o.All, Compatibility: o.Compatibility, ProjectOptionsFns: po, LoadListeners: []api.LoadListener{metricsListener}, OCI: api.OCIOptions{ InsecureRegistries: o.insecureRegistries, }, } project, err := backend.LoadProject(ctx, loadOpts) if err != nil { return nil, metrics, err } return project, metrics, nil } func (o *ProjectOptions) remoteLoaders(dockerCli command.Cli) []loader.ResourceLoader { if o.Offline { return nil } git := remote.NewGitRemoteLoader(dockerCli, o.Offline) oci := remote.NewOCIRemoteLoader(dockerCli, o.Offline, api.OCIOptions{}) return []loader.ResourceLoader{git, oci} } func (o *ProjectOptions) toProjectOptions(po ...cli.ProjectOptionsFn) (*cli.ProjectOptions, error) { opts := []cli.ProjectOptionsFn{ cli.WithWorkingDirectory(o.ProjectDir), // First apply os.Environment, always win cli.WithOsEnv, } if _, present := os.LookupEnv("PWD"); !present { if pwd, err := os.Getwd(); err != nil { return nil, err } else { opts = append(opts, cli.WithEnv([]string{"PWD=" + pwd})) } } opts = append(opts, // Load PWD/.env if present and no explicit --env-file has been set cli.WithEnvFiles(o.EnvFiles...), // read dot env file to populate project environment cli.WithDotEnv, // get compose file path set by COMPOSE_FILE cli.WithConfigFileEnv, // if none was selected, get default compose.yaml file from current dir or parent folder cli.WithDefaultConfigPath, // .. and then, a project directory != PWD maybe has been set so let's load .env file cli.WithEnvFiles(o.EnvFiles...), //nolint:gocritic // intentionally applying cli.WithEnvFiles twice. cli.WithDotEnv, //nolint:gocritic // intentionally applying cli.WithDotEnv twice. // eventually COMPOSE_PROFILES should have been set cli.WithDefaultProfiles(o.Profiles...), cli.WithName(o.ProjectName), ) return cli.NewProjectOptions(o.ConfigPaths, append(po, opts...)...) } // PluginName is the name of the plugin const PluginName = "compose" // RunningAsStandalone detects when running as a standalone program func RunningAsStandalone() bool { return len(os.Args) < 2 || os.Args[1] != metadata.MetadataSubcommandName && os.Args[1] != PluginName } type BackendOptions struct { Options []compose.Option } func (o *BackendOptions) Add(option compose.Option) { o.Options = append(o.Options, option) } // RootCommand returns the compose command with its child commands func RootCommand(dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { //nolint:gocyclo // filter out useless commandConn.CloseWrite warning message that can occur // when using a remote context that is unreachable: "commandConn.CloseWrite: commandconn: failed to wait: signal: killed" // https://github.com/docker/cli/blob/e1f24d3c93df6752d3c27c8d61d18260f141310c/cli/connhelper/commandconn/commandconn.go#L203-L215 logrus.AddHook(logutil.NewFilter([]logrus.Level{ logrus.WarnLevel, }, "commandConn.CloseWrite:", "commandConn.CloseRead:", )) opts := ProjectOptions{} var ( ansi string noAnsi bool verbose bool version bool parallel int dryRun bool ) c := &cobra.Command{ Short: "Docker Compose", Long: "Define and run multi-container applications with Docker", Use: PluginName, TraverseChildren: true, // By default (no Run/RunE in parent c) for typos in subcommands, cobra displays the help of parent c but exit(0) ! RunE: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { return cmd.Help() } if version { return versionCommand(dockerCli).Execute() } _ = cmd.Help() return dockercli.StatusError{ StatusCode: 1, Status: fmt.Sprintf("unknown docker command: %q", "compose "+args[0]), } }, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { parent := cmd.Root() if parent != nil { parentPrerun := parent.PersistentPreRunE if parentPrerun != nil { err := parentPrerun(cmd, args) if err != nil { return err } } } if verbose { logrus.SetLevel(logrus.TraceLevel) } err := setEnvWithDotEnv(opts) if err != nil { return err } if noAnsi { if ansi != "auto" { return errors.New(`cannot specify DEPRECATED "--no-ansi" and "--ansi". Please use only "--ansi"`) } ansi = "never" fmt.Fprint(os.Stderr, "option '--no-ansi' is DEPRECATED ! Please use '--ansi' instead.\n") } if v, ok := os.LookupEnv("COMPOSE_ANSI"); ok && !cmd.Flags().Changed("ansi") { ansi = v } formatter.SetANSIMode(dockerCli, ansi) if noColor, ok := os.LookupEnv("NO_COLOR"); ok && noColor != "" { display.NoColor() formatter.SetANSIMode(dockerCli, formatter.Never) } switch ansi { case "never": display.Mode = display.ModePlain case "always": display.Mode = display.ModeTTY } var ep api.EventProcessor switch opts.Progress { case "", display.ModeAuto: switch { case ansi == "never": display.Mode = display.ModePlain ep = display.Plain(dockerCli.Err()) case dockerCli.Out().IsTerminal(): ep = display.Full(dockerCli.Err(), stdinfo(dockerCli)) default: ep = display.Plain(dockerCli.Err()) } case display.ModeTTY: if ansi == "never" { return fmt.Errorf("can't use --progress tty while ANSI support is disabled") } display.Mode = display.ModeTTY ep = display.Full(dockerCli.Err(), stdinfo(dockerCli)) case display.ModePlain: if ansi == "always" { return fmt.Errorf("can't use --progress plain while ANSI support is forced") } display.Mode = display.ModePlain ep = display.Plain(dockerCli.Err()) case display.ModeQuiet, "none": display.Mode = display.ModeQuiet ep = display.Quiet() case display.ModeJSON: display.Mode = display.ModeJSON logrus.SetFormatter(&logrus.JSONFormatter{}) ep = display.JSON(dockerCli.Err()) default: return fmt.Errorf("unsupported --progress value %q", opts.Progress) } backendOptions.Add(compose.WithEventProcessor(ep)) // (4) options validation / normalization if opts.WorkDir != "" { if opts.ProjectDir != "" { return errors.New(`cannot specify DEPRECATED "--workdir" and "--project-directory". Please use only "--project-directory" instead`) } opts.ProjectDir = opts.WorkDir fmt.Fprint(os.Stderr, aec.Apply("option '--workdir' is DEPRECATED at root level! Please use '--project-directory' instead.\n", aec.RedF)) } for i, file := range opts.EnvFiles { if !filepath.IsAbs(file) { file, err := filepath.Abs(file) if err != nil { return err } opts.EnvFiles[i] = file } } composeCmd := cmd for composeCmd.Name() != PluginName { if !composeCmd.HasParent() { return fmt.Errorf("error parsing command line, expected %q", PluginName) } composeCmd = composeCmd.Parent() } if v, ok := os.LookupEnv(ComposeParallelLimit); ok && !composeCmd.Flags().Changed("parallel") { i, err := strconv.Atoi(v) if err != nil { return fmt.Errorf("%s must be an integer (found: %q)", ComposeParallelLimit, v) } parallel = i } if parallel > 0 { logrus.Debugf("Limiting max concurrency to %d jobs", parallel) backendOptions.Add(compose.WithMaxConcurrency(parallel)) } // dry run detection if dryRun { backendOptions.Add(compose.WithDryRun) } return nil }, } c.AddCommand( upCommand(&opts, dockerCli, backendOptions), downCommand(&opts, dockerCli, backendOptions), startCommand(&opts, dockerCli, backendOptions), restartCommand(&opts, dockerCli, backendOptions), stopCommand(&opts, dockerCli, backendOptions), psCommand(&opts, dockerCli, backendOptions), listCommand(dockerCli, backendOptions), logsCommand(&opts, dockerCli, backendOptions), configCommand(&opts, dockerCli), killCommand(&opts, dockerCli, backendOptions), runCommand(&opts, dockerCli, backendOptions), removeCommand(&opts, dockerCli, backendOptions), execCommand(&opts, dockerCli, backendOptions), attachCommand(&opts, dockerCli, backendOptions), exportCommand(&opts, dockerCli, backendOptions), commitCommand(&opts, dockerCli, backendOptions), pauseCommand(&opts, dockerCli, backendOptions), unpauseCommand(&opts, dockerCli, backendOptions), topCommand(&opts, dockerCli, backendOptions), eventsCommand(&opts, dockerCli, backendOptions), portCommand(&opts, dockerCli, backendOptions), imagesCommand(&opts, dockerCli, backendOptions), versionCommand(dockerCli), buildCommand(&opts, dockerCli, backendOptions), pushCommand(&opts, dockerCli, backendOptions), pullCommand(&opts, dockerCli, backendOptions), createCommand(&opts, dockerCli, backendOptions), copyCommand(&opts, dockerCli, backendOptions), waitCommand(&opts, dockerCli, backendOptions), scaleCommand(&opts, dockerCli, backendOptions), statsCommand(&opts, dockerCli), watchCommand(&opts, dockerCli, backendOptions), publishCommand(&opts, dockerCli, backendOptions), alphaCommand(&opts, dockerCli, backendOptions), bridgeCommand(&opts, dockerCli), volumesCommand(&opts, dockerCli, backendOptions), ) c.Flags().SetInterspersed(false) opts.addProjectFlags(c.Flags()) c.RegisterFlagCompletionFunc( //nolint:errcheck "project-name", completeProjectNames(dockerCli, backendOptions), ) c.RegisterFlagCompletionFunc( //nolint:errcheck "project-directory", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{}, cobra.ShellCompDirectiveFilterDirs }, ) c.RegisterFlagCompletionFunc( //nolint:errcheck "file", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{"yaml", "yml"}, cobra.ShellCompDirectiveFilterFileExt }, ) c.RegisterFlagCompletionFunc( //nolint:errcheck "profile", completeProfileNames(dockerCli, &opts), ) c.RegisterFlagCompletionFunc( //nolint:errcheck "progress", cobra.FixedCompletions(printerModes, cobra.ShellCompDirectiveNoFileComp), ) c.Flags().StringVar(&ansi, "ansi", "auto", `Control when to print ANSI control characters ("never"|"always"|"auto")`) c.Flags().IntVar(&parallel, "parallel", -1, `Control max parallelism, -1 for unlimited`) c.Flags().BoolVarP(&version, "version", "v", false, "Show the Docker Compose version information") c.PersistentFlags().BoolVar(&dryRun, "dry-run", false, "Execute command in dry run mode") c.Flags().MarkHidden("version") //nolint:errcheck c.Flags().BoolVar(&noAnsi, "no-ansi", false, `Do not print ANSI control characters (DEPRECATED)`) c.Flags().MarkHidden("no-ansi") //nolint:errcheck c.Flags().BoolVar(&verbose, "verbose", false, "Show more output") c.Flags().MarkHidden("verbose") //nolint:errcheck return c } func stdinfo(dockerCli command.Cli) io.Writer { if stdioToStdout { return dockerCli.Out() } return dockerCli.Err() } func setEnvWithDotEnv(opts ProjectOptions) error { options, err := cli.NewProjectOptions(opts.ConfigPaths, cli.WithWorkingDirectory(opts.ProjectDir), cli.WithOsEnv, cli.WithEnvFiles(opts.EnvFiles...), cli.WithDotEnv, ) if err != nil { return err } envFromFile, err := dotenv.GetEnvFromFile(composegoutils.GetAsEqualsMap(os.Environ()), options.EnvFiles) if err != nil { return err } for k, v := range envFromFile { if _, ok := os.LookupEnv(k); !ok && strings.HasPrefix(k, "COMPOSE_") { if err := os.Setenv(k, v); err != nil { return err } } } return nil } var printerModes = []string{ display.ModeAuto, display.ModeTTY, display.ModePlain, display.ModeJSON, display.ModeQuiet, }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/options.go
cmd/compose/options.go
/* Copyright 2023 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 ( "context" "fmt" "io" "os" "slices" "sort" "strings" "text/tabwriter" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/template" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/docker/compose/v5/cmd/display" "github.com/docker/compose/v5/cmd/prompt" "github.com/docker/compose/v5/internal/tracing" ) func applyPlatforms(project *types.Project, buildForSinglePlatform bool) error { defaultPlatform := project.Environment["DOCKER_DEFAULT_PLATFORM"] for name, service := range project.Services { if service.Build == nil { continue } // default platform only applies if the service doesn't specify if defaultPlatform != "" && service.Platform == "" { if len(service.Build.Platforms) > 0 && !slices.Contains(service.Build.Platforms, defaultPlatform) { return fmt.Errorf("service %q build.platforms does not support value set by DOCKER_DEFAULT_PLATFORM: %s", name, defaultPlatform) } service.Platform = defaultPlatform } if service.Platform != "" { if len(service.Build.Platforms) > 0 { if !slices.Contains(service.Build.Platforms, service.Platform) { return fmt.Errorf("service %q build configuration does not support platform: %s", name, service.Platform) } } if buildForSinglePlatform || len(service.Build.Platforms) == 0 { // if we're building for a single platform, we want to build for the platform we'll use to run the image // similarly, if no build platforms were explicitly specified, it makes sense to build for the platform // the image is designed for rather than allowing the builder to infer the platform service.Build.Platforms = []string{service.Platform} } } // services can specify that they should be built for multiple platforms, which can be used // with `docker compose build` to produce a multi-arch image // other cases, such as `up` and `run`, need a single architecture to actually run // if there is only a single platform present (which might have been inferred // from service.Platform above), it will be used, even if it requires emulation. // if there's more than one platform, then the list is cleared so that the builder // can decide. // TODO(milas): there's no validation that the platform the builder will pick is actually one // of the supported platforms from the build definition // e.g. `build.platforms: [linux/arm64, linux/amd64]` on a `linux/ppc64` machine would build // for `linux/ppc64` instead of returning an error that it's not a valid platform for the service. if buildForSinglePlatform && len(service.Build.Platforms) > 1 { // empty indicates that the builder gets to decide service.Build.Platforms = nil } project.Services[name] = service } return nil } // isRemoteConfig checks if the main compose file is from a remote source (OCI or Git) func isRemoteConfig(dockerCli command.Cli, options buildOptions) bool { if len(options.ConfigPaths) == 0 { return false } remoteLoaders := options.remoteLoaders(dockerCli) for _, loader := range remoteLoaders { if loader.Accept(options.ConfigPaths[0]) { return true } } return false } // checksForRemoteStack handles environment variable prompts for remote configurations func checksForRemoteStack(ctx context.Context, dockerCli command.Cli, project *types.Project, options buildOptions, assumeYes bool, cmdEnvs []string) error { if !isRemoteConfig(dockerCli, options) { return nil } if metrics, ok := ctx.Value(tracing.MetricsKey{}).(tracing.Metrics); ok && metrics.CountIncludesRemote > 0 { if err := confirmRemoteIncludes(dockerCli, options, assumeYes); err != nil { return err } } displayLocationRemoteStack(dockerCli, project, options) return promptForInterpolatedVariables(ctx, dockerCli, options.ProjectOptions, assumeYes, cmdEnvs) } // Prepare the values map and collect all variables info type varInfo struct { name string value string source string required bool defaultValue string } // promptForInterpolatedVariables displays all variables and their values at once, // then prompts for confirmation func promptForInterpolatedVariables(ctx context.Context, dockerCli command.Cli, projectOptions *ProjectOptions, assumeYes bool, cmdEnvs []string) error { if assumeYes { return nil } varsInfo, noVariables, err := extractInterpolationVariablesFromModel(ctx, dockerCli, projectOptions, cmdEnvs) if err != nil { return err } if noVariables { return nil } displayInterpolationVariables(dockerCli.Out(), varsInfo) // Prompt for confirmation userInput := prompt.NewPrompt(dockerCli.In(), dockerCli.Out()) msg := "\nDo you want to proceed with these variables? [Y/n]: " confirmed, err := userInput.Confirm(msg, true) if err != nil { return err } if !confirmed { return fmt.Errorf("operation cancelled by user") } return nil } func extractInterpolationVariablesFromModel(ctx context.Context, dockerCli command.Cli, projectOptions *ProjectOptions, cmdEnvs []string) ([]varInfo, bool, error) { cmdEnvMap := extractEnvCLIDefined(cmdEnvs) // Create a model without interpolation to extract variables opts := configOptions{ noInterpolate: true, ProjectOptions: projectOptions, } model, err := opts.ToModel(ctx, dockerCli, nil, cli.WithoutEnvironmentResolution) if err != nil { return nil, false, err } // Extract variables that need interpolation variables := template.ExtractVariables(model, template.DefaultPattern) if len(variables) == 0 { return nil, true, nil } var varsInfo []varInfo proposedValues := make(map[string]string) for name, variable := range variables { info := varInfo{ name: name, required: variable.Required, defaultValue: variable.DefaultValue, } // Determine value and source based on priority if value, exists := cmdEnvMap[name]; exists { info.value = value info.source = "command-line" proposedValues[name] = value } else if value, exists := os.LookupEnv(name); exists { info.value = value info.source = "environment" proposedValues[name] = value } else if variable.DefaultValue != "" { info.value = variable.DefaultValue info.source = "compose file" proposedValues[name] = variable.DefaultValue } else { info.value = "<unset>" info.source = "none" } varsInfo = append(varsInfo, info) } return varsInfo, false, nil } func extractEnvCLIDefined(cmdEnvs []string) map[string]string { // Parse command-line environment variables cmdEnvMap := make(map[string]string) for _, env := range cmdEnvs { parts := strings.SplitN(env, "=", 2) if len(parts) == 2 { cmdEnvMap[parts[0]] = parts[1] } } return cmdEnvMap } func displayInterpolationVariables(writer io.Writer, varsInfo []varInfo) { // Display all variables in a table format _, _ = fmt.Fprintln(writer, "\nFound the following variables in configuration:") w := tabwriter.NewWriter(writer, 0, 0, 3, ' ', 0) _, _ = fmt.Fprintln(w, "VARIABLE\tVALUE\tSOURCE\tREQUIRED\tDEFAULT") sort.Slice(varsInfo, func(a, b int) bool { return varsInfo[a].name < varsInfo[b].name }) for _, info := range varsInfo { required := "no" if info.required { required = "yes" } _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", info.name, info.value, info.source, required, info.defaultValue, ) } _ = w.Flush() } func displayLocationRemoteStack(dockerCli command.Cli, project *types.Project, options buildOptions) { mainComposeFile := options.ProjectOptions.ConfigPaths[0] //nolint:staticcheck if display.Mode != display.ModeQuiet && display.Mode != display.ModeJSON { _, _ = fmt.Fprintf(dockerCli.Out(), "Your compose stack %q is stored in %q\n", mainComposeFile, project.WorkingDir) } } func confirmRemoteIncludes(dockerCli command.Cli, options buildOptions, assumeYes bool) error { if assumeYes { return nil } var remoteIncludes []string remoteLoaders := options.ProjectOptions.remoteLoaders(dockerCli) //nolint:staticcheck for _, cf := range options.ProjectOptions.ConfigPaths { //nolint:staticcheck for _, loader := range remoteLoaders { if loader.Accept(cf) { remoteIncludes = append(remoteIncludes, cf) break } } } if len(remoteIncludes) == 0 { return nil } _, _ = fmt.Fprintln(dockerCli.Out(), "\nWarning: This Compose project includes files from remote sources:") for _, include := range remoteIncludes { _, _ = fmt.Fprintf(dockerCli.Out(), " - %s\n", include) } _, _ = fmt.Fprintln(dockerCli.Out(), "\nRemote includes could potentially be malicious. Make sure you trust the source.") msg := "Do you want to continue? [y/N]: " confirmed, err := prompt.NewPrompt(dockerCli.In(), dockerCli.Out()).Confirm(msg, false) if err != nil { return err } if !confirmed { return fmt.Errorf("operation cancelled by user") } return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/scale.go
cmd/compose/scale.go
/* 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 ( "context" "fmt" "maps" "slices" "strconv" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type scaleOptions struct { *ProjectOptions noDeps bool } func scaleCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := scaleOptions{ ProjectOptions: p, } scaleCmd := &cobra.Command{ Use: "scale [SERVICE=REPLICAS...]", Short: "Scale services ", Args: cobra.MinimumNArgs(1), RunE: Adapt(func(ctx context.Context, args []string) error { serviceTuples, err := parseServicesReplicasArgs(args) if err != nil { return err } return runScale(ctx, dockerCli, backendOptions, opts, serviceTuples) }), ValidArgsFunction: completeScaleArgs(dockerCli, p), } flags := scaleCmd.Flags() flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't start linked services") return scaleCmd } func runScale(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts scaleOptions, serviceReplicaTuples map[string]int) error { backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } services := slices.Sorted(maps.Keys(serviceReplicaTuples)) project, _, err := opts.ToProject(ctx, dockerCli, backend, services) if err != nil { return err } if opts.noDeps { if project, err = project.WithSelectedServices(services, types.IgnoreDependencies); err != nil { return err } } for key, value := range serviceReplicaTuples { service, err := project.GetService(key) if err != nil { return err } service.SetScale(value) project.Services[key] = service } return backend.Scale(ctx, project, api.ScaleOptions{Services: services}) } func parseServicesReplicasArgs(args []string) (map[string]int, error) { serviceReplicaTuples := map[string]int{} for _, arg := range args { key, val, ok := strings.Cut(arg, "=") if !ok || key == "" || val == "" { return nil, fmt.Errorf("invalid scale specifier: %s", arg) } intValue, err := strconv.Atoi(val) if err != nil { return nil, fmt.Errorf("invalid scale specifier: can't parse replica value as int: %v", arg) } serviceReplicaTuples[key] = intValue } return serviceReplicaTuples, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/logs.go
cmd/compose/logs.go
/* 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 ( "context" "errors" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type logsOptions struct { *ProjectOptions composeOptions follow bool index int tail string since string until string noColor bool noPrefix bool timestamps bool } func logsCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := logsOptions{ ProjectOptions: p, } logsCmd := &cobra.Command{ Use: "logs [OPTIONS] [SERVICE...]", Short: "View output from containers", RunE: Adapt(func(ctx context.Context, args []string) error { return runLogs(ctx, dockerCli, backendOptions, opts, args) }), PreRunE: func(cmd *cobra.Command, args []string) error { if opts.index > 0 && len(args) != 1 { return errors.New("--index requires one service to be selected") } return nil }, ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := logsCmd.Flags() flags.BoolVarP(&opts.follow, "follow", "f", false, "Follow log output") flags.IntVar(&opts.index, "index", 0, "index of the container if service has multiple replicas") flags.StringVar(&opts.since, "since", "", "Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)") flags.StringVar(&opts.until, "until", "", "Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)") flags.BoolVar(&opts.noColor, "no-color", false, "Produce monochrome output") flags.BoolVar(&opts.noPrefix, "no-log-prefix", false, "Don't print prefix in logs") flags.BoolVarP(&opts.timestamps, "timestamps", "t", false, "Show timestamps") flags.StringVarP(&opts.tail, "tail", "n", "all", "Number of lines to show from the end of the logs for each container") return logsCmd } func runLogs(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts logsOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } // exclude services configured to ignore output (attach: false), until explicitly selected if project != nil && len(services) == 0 { for n, service := range project.Services { if service.Attach == nil || *service.Attach { services = append(services, n) } } } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } consumer := formatter.NewLogConsumer(ctx, dockerCli.Out(), dockerCli.Err(), !opts.noColor, !opts.noPrefix, false) return backend.Logs(ctx, name, consumer, api.LogOptions{ Project: project, Services: services, Follow: opts.follow, Index: opts.index, Tail: opts.tail, Since: opts.since, Until: opts.until, Timestamps: opts.timestamps, }) } var _ api.LogConsumer = &logConsumer{} type logConsumer struct { events api.EventProcessor } func (l logConsumer) Log(containerName, message string) { l.events.On(api.Resource{ ID: containerName, Text: message, }) } func (l logConsumer) Err(containerName, message string) { l.events.On(api.Resource{ ID: containerName, Status: api.Error, Text: message, }) } func (l logConsumer) Status(containerName, message string) { l.events.On(api.Resource{ ID: containerName, Status: api.Error, Text: message, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/completion.go
cmd/compose/completion.go
/* 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 ( "sort" "strings" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) // validArgsFn defines a completion func to be returned to fetch completion options type validArgsFn func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) func noCompletion() validArgsFn { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return []string{}, cobra.ShellCompDirectiveNoSpace } } func completeServiceNames(dockerCli command.Cli, p *ProjectOptions) validArgsFn { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { p.Offline = true backend, err := compose.NewComposeService(dockerCli) if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } project, _, err := p.ToProject(cmd.Context(), dockerCli, backend, nil) if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } var values []string serviceNames := append(project.ServiceNames(), project.DisabledServiceNames()...) for _, s := range serviceNames { if toComplete == "" || strings.HasPrefix(s, toComplete) { values = append(values, s) } } return values, cobra.ShellCompDirectiveNoFileComp } } func completeProjectNames(dockerCli command.Cli, backendOptions *BackendOptions) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return nil, cobra.ShellCompDirectiveError } list, err := backend.List(cmd.Context(), api.ListOptions{ All: true, }) if err != nil { return nil, cobra.ShellCompDirectiveError } var values []string for _, stack := range list { if strings.HasPrefix(stack.Name, toComplete) { values = append(values, stack.Name) } } return values, cobra.ShellCompDirectiveNoFileComp } } func completeProfileNames(dockerCli command.Cli, p *ProjectOptions) validArgsFn { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { p.Offline = true backend, err := compose.NewComposeService(dockerCli) if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } project, _, err := p.ToProject(cmd.Context(), dockerCli, backend, nil) if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp } allProfileNames := project.AllServices().GetProfiles() sort.Strings(allProfileNames) var values []string for _, profileName := range allProfileNames { if strings.HasPrefix(profileName, toComplete) { values = append(values, profileName) } } return values, cobra.ShellCompDirectiveNoFileComp } } func completeScaleArgs(cli command.Cli, p *ProjectOptions) cobra.CompletionFunc { return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { completions, directive := completeServiceNames(cli, p)(cmd, args, toComplete) for i, completion := range completions { completions[i] = completion + "=" } return completions, directive } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/export.go
cmd/compose/export.go
/* 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 ( "context" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type exportOptions struct { *ProjectOptions service string output string index int } func exportCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { options := exportOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "export [OPTIONS] SERVICE", Short: "Export a service container's filesystem as a tar archive", Args: cobra.MinimumNArgs(1), PreRunE: Adapt(func(ctx context.Context, args []string) error { options.service = args[0] return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { return runExport(ctx, dockerCli, backendOptions, options) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.IntVar(&options.index, "index", 0, "index of the container if service has multiple replicas.") flags.StringVarP(&options.output, "output", "o", "", "Write to a file, instead of STDOUT") return cmd } func runExport(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, options exportOptions) error { projectName, err := options.toProjectName(ctx, dockerCli) if err != nil { return err } exportOptions := api.ExportOptions{ Service: options.service, Index: options.index, Output: options.output, } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Export(ctx, projectName, exportOptions) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/run.go
cmd/compose/run.go
/* 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 ( "context" "fmt" "os" "strings" composecli "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/dotenv" "github.com/compose-spec/compose-go/v2/format" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/docker/cli/opts" "github.com/mattn/go-shellwords" xprogress "github.com/moby/buildkit/util/progress/progressui" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/cmd/display" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" "github.com/docker/compose/v5/pkg/utils" ) type runOptions struct { *composeOptions Service string Command []string environment []string envFiles []string Detach bool Remove bool noTty bool interactive bool user string workdir string entrypoint string entrypointCmd []string capAdd opts.ListOpts capDrop opts.ListOpts labels []string volumes []string publish []string useAliases bool servicePorts bool name string noDeps bool ignoreOrphans bool removeOrphans bool quiet bool quietPull bool } func (options runOptions) apply(project *types.Project) (*types.Project, error) { if options.noDeps { var err error project, err = project.WithSelectedServices([]string{options.Service}, types.IgnoreDependencies) if err != nil { return nil, err } } target, err := project.GetService(options.Service) if err != nil { return nil, err } target.Tty = !options.noTty target.StdinOpen = options.interactive // --service-ports and --publish are incompatible if !options.servicePorts { if len(target.Ports) > 0 { logrus.Debug("Running service without ports exposed as --service-ports=false") } target.Ports = []types.ServicePortConfig{} for _, p := range options.publish { config, err := types.ParsePortConfig(p) if err != nil { return nil, err } target.Ports = append(target.Ports, config...) } } for _, v := range options.volumes { volume, err := format.ParseVolume(v) if err != nil { return nil, err } target.Volumes = append(target.Volumes, volume) } for name := range project.Services { if name == options.Service { project.Services[name] = target break } } return project, nil } func (options runOptions) getEnvironment(resolve func(string) (string, bool)) (types.Mapping, error) { environment := types.NewMappingWithEquals(options.environment).Resolve(resolve).ToMapping() for _, file := range options.envFiles { f, err := os.Open(file) if err != nil { return nil, err } vars, err := dotenv.ParseWithLookup(f, func(k string) (string, bool) { value, ok := environment[k] return value, ok }) if err != nil { return nil, nil } for k, v := range vars { if _, ok := environment[k]; !ok { environment[k] = v } } } return environment, nil } func runCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { options := runOptions{ composeOptions: &composeOptions{ ProjectOptions: p, }, capAdd: opts.NewListOpts(nil), capDrop: opts.NewListOpts(nil), } createOpts := createOptions{} buildOpts := buildOptions{ ProjectOptions: p, } // We remove the attribute from the option struct and use a dedicated var, to limit confusion and avoid anyone to use options.tty. // The tty flag is here for convenience and let user do "docker compose run -it" the same way as they use the "docker run" command. var ttyFlag bool cmd := &cobra.Command{ Use: "run [OPTIONS] SERVICE [COMMAND] [ARGS...]", Short: "Run a one-off command on a service", Args: cobra.MinimumNArgs(1), PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { options.Service = args[0] if len(args) > 1 { options.Command = args[1:] } if len(options.publish) > 0 && options.servicePorts { return fmt.Errorf("--service-ports and --publish are incompatible") } if cmd.Flags().Changed("entrypoint") { command, err := shellwords.Parse(options.entrypoint) if err != nil { return err } options.entrypointCmd = command } if cmd.Flags().Changed("tty") { if cmd.Flags().Changed("no-TTY") { return fmt.Errorf("--tty and --no-TTY can't be used together") } else { options.noTty = !ttyFlag } } else if !cmd.Flags().Changed("no-TTY") && !cmd.Flags().Changed("interactive") && !dockerCli.In().IsTerminal() { // while `docker run` requires explicit `-it` flags, Compose enables interactive mode and TTY by default // but when compose is used from a script that has stdin piped from another command, we just can't // Here, we detect we run "by default" (user didn't passed explicit flags) and disable TTY allocation if // we don't have an actual terminal to attach to for interactive mode options.noTty = true } if options.quiet { display.Mode = display.ModeQuiet backendOptions.Add(compose.WithEventProcessor(display.Quiet())) } createOpts.pullChanged = cmd.Flags().Changed("pull") return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, _, err := p.ToProject(ctx, dockerCli, backend, []string{options.Service}, composecli.WithoutEnvironmentResolution) if err != nil { return err } project, err = project.WithServicesEnvironmentResolved(true) if err != nil { return err } if createOpts.quietPull { buildOpts.Progress = string(xprogress.QuietMode) } options.ignoreOrphans = utils.StringToBool(project.Environment[ComposeIgnoreOrphans]) return runRun(ctx, backend, project, options, createOpts, buildOpts, dockerCli) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.BoolVarP(&options.Detach, "detach", "d", false, "Run container in background and print container ID") flags.StringArrayVarP(&options.environment, "env", "e", []string{}, "Set environment variables") flags.StringArrayVar(&options.envFiles, "env-from-file", []string{}, "Set environment variables from file") flags.StringArrayVarP(&options.labels, "label", "l", []string{}, "Add or override a label") flags.BoolVar(&options.Remove, "rm", false, "Automatically remove the container when it exits") flags.BoolVarP(&options.noTty, "no-TTY", "T", !dockerCli.Out().IsTerminal(), "Disable pseudo-TTY allocation (default: auto-detected)") flags.StringVar(&options.name, "name", "", "Assign a name to the container") flags.StringVarP(&options.user, "user", "u", "", "Run as specified username or uid") flags.StringVarP(&options.workdir, "workdir", "w", "", "Working directory inside the container") flags.StringVar(&options.entrypoint, "entrypoint", "", "Override the entrypoint of the image") flags.Var(&options.capAdd, "cap-add", "Add Linux capabilities") flags.Var(&options.capDrop, "cap-drop", "Drop Linux capabilities") flags.BoolVar(&options.noDeps, "no-deps", false, "Don't start linked services") flags.StringArrayVarP(&options.volumes, "volume", "v", []string{}, "Bind mount a volume") flags.StringArrayVarP(&options.publish, "publish", "p", []string{}, "Publish a container's port(s) to the host") flags.BoolVar(&options.useAliases, "use-aliases", false, "Use the service's network useAliases in the network(s) the container connects to") flags.BoolVarP(&options.servicePorts, "service-ports", "P", false, "Run command with all service's ports enabled and mapped to the host") flags.StringVar(&createOpts.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never")`) flags.BoolVarP(&options.quiet, "quiet", "q", false, "Don't print anything to STDOUT") flags.BoolVar(&buildOpts.quiet, "quiet-build", false, "Suppress progress output from the build process") flags.BoolVar(&options.quietPull, "quiet-pull", false, "Pull without printing progress information") flags.BoolVar(&createOpts.Build, "build", false, "Build image before starting container") flags.BoolVar(&options.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file") cmd.Flags().BoolVarP(&options.interactive, "interactive", "i", true, "Keep STDIN open even if not attached") cmd.Flags().BoolVarP(&ttyFlag, "tty", "t", true, "Allocate a pseudo-TTY") cmd.Flags().MarkHidden("tty") //nolint:errcheck flags.SetNormalizeFunc(normalizeRunFlags) flags.SetInterspersed(false) return cmd } func normalizeRunFlags(f *pflag.FlagSet, name string) pflag.NormalizedName { switch name { case "volumes": name = "volume" case "labels": name = "label" } return pflag.NormalizedName(name) } func runRun(ctx context.Context, backend api.Compose, project *types.Project, options runOptions, createOpts createOptions, buildOpts buildOptions, dockerCli command.Cli) error { project, err := options.apply(project) if err != nil { return err } err = createOpts.Apply(project) if err != nil { return err } if err := checksForRemoteStack(ctx, dockerCli, project, buildOpts, createOpts.AssumeYes, []string{}); err != nil { return err } labels := types.Labels{} for _, s := range options.labels { parts := strings.SplitN(s, "=", 2) if len(parts) != 2 { return fmt.Errorf("label must be set as KEY=VALUE") } labels[parts[0]] = parts[1] } var buildForRun *api.BuildOptions if !createOpts.noBuild { bo, err := buildOpts.toAPIBuildOptions(nil) if err != nil { return err } buildForRun = &bo } environment, err := options.getEnvironment(project.Environment.Resolve) if err != nil { return err } // start container and attach to container streams runOpts := api.RunOptions{ CreateOptions: api.CreateOptions{ Build: buildForRun, RemoveOrphans: options.removeOrphans, IgnoreOrphans: options.ignoreOrphans, QuietPull: options.quietPull, }, Name: options.name, Service: options.Service, Command: options.Command, Detach: options.Detach, AutoRemove: options.Remove, Tty: !options.noTty, Interactive: options.interactive, WorkingDir: options.workdir, User: options.user, CapAdd: options.capAdd.GetSlice(), CapDrop: options.capDrop.GetSlice(), Environment: environment.Values(), Entrypoint: options.entrypointCmd, Labels: labels, UseNetworkAliases: options.useAliases, NoDeps: options.noDeps, Index: 0, } for name, service := range project.Services { if name == options.Service { service.StdinOpen = options.interactive project.Services[name] = service } } exitCode, err := backend.RunOneOffContainer(ctx, project, runOpts) if exitCode != 0 { errMsg := "" if err != nil { errMsg = err.Error() } return cli.StatusError{StatusCode: exitCode, Status: errMsg} } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/pullOptions_test.go
cmd/compose/pullOptions_test.go
/* Copyright 2023 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 ( "testing" "github.com/compose-spec/compose-go/v2/types" "gotest.tools/v3/assert" ) func TestApplyPullOptions(t *testing.T) { project := &types.Project{ Services: types.Services{ "must-build": { Name: "must-build", // No image, local build only Build: &types.BuildConfig{ Context: ".", }, }, "has-build": { Name: "has-build", Image: "registry.example.com/myservice", Build: &types.BuildConfig{ Context: ".", }, }, "must-pull": { Name: "must-pull", Image: "registry.example.com/another-service", }, }, } project, err := pullOptions{ policy: types.PullPolicyMissing, }.apply(project, nil) assert.NilError(t, err) assert.Equal(t, project.Services["must-build"].PullPolicy, "") // still default assert.Equal(t, project.Services["has-build"].PullPolicy, types.PullPolicyMissing) assert.Equal(t, project.Services["must-pull"].PullPolicy, types.PullPolicyMissing) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/volumes.go
cmd/compose/volumes.go
/* 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 ( "context" "fmt" "slices" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/command/formatter" "github.com/docker/cli/cli/flags" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type volumesOptions struct { *ProjectOptions Quiet bool Format string } func volumesCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { options := volumesOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "volumes [OPTIONS] [SERVICE...]", Short: "List volumes", RunE: Adapt(func(ctx context.Context, args []string) error { return runVol(ctx, dockerCli, backendOptions, args, options) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } cmd.Flags().BoolVarP(&options.Quiet, "quiet", "q", false, "Only display volume names") cmd.Flags().StringVar(&options.Format, "format", "table", flags.FormatHelp) return cmd } func runVol(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, services []string, options volumesOptions) error { project, name, err := options.projectOrName(ctx, dockerCli, services...) if err != nil { return err } if project != nil { names := project.ServiceNames() for _, service := range services { if !slices.Contains(names, service) { return fmt.Errorf("no such service: %s", service) } } } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } volumes, err := backend.Volumes(ctx, name, api.VolumesOptions{ Services: services, }) if err != nil { return err } if options.Quiet { for _, v := range volumes { _, _ = fmt.Fprintln(dockerCli.Out(), v.Name) } return nil } volumeCtx := formatter.Context{ Output: dockerCli.Out(), Format: formatter.NewVolumeFormat(options.Format, options.Quiet), } return formatter.VolumeWrite(volumeCtx, volumes) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/cp.go
cmd/compose/cp.go
/* 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 ( "context" "errors" "github.com/docker/cli/cli" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type copyOptions struct { *ProjectOptions source string destination string index int all bool followLink bool copyUIDGID bool } func copyCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := copyOptions{ ProjectOptions: p, } copyCmd := &cobra.Command{ Use: `cp [OPTIONS] SERVICE:SRC_PATH DEST_PATH|- docker compose cp [OPTIONS] SRC_PATH|- SERVICE:DEST_PATH`, Short: "Copy files/folders between a service container and the local filesystem", Args: cli.ExactArgs(2), PreRunE: Adapt(func(ctx context.Context, args []string) error { if args[0] == "" { return errors.New("source can not be empty") } if args[1] == "" { return errors.New("destination can not be empty") } return nil }), RunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { opts.source = args[0] opts.destination = args[1] return runCopy(ctx, dockerCli, backendOptions, opts) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := copyCmd.Flags() flags.IntVar(&opts.index, "index", 0, "Index of the container if service has multiple replicas") flags.BoolVar(&opts.all, "all", false, "Include containers created by the run command") flags.BoolVarP(&opts.followLink, "follow-link", "L", false, "Always follow symbol link in SRC_PATH") flags.BoolVarP(&opts.copyUIDGID, "archive", "a", false, "Archive mode (copy all uid/gid information)") return copyCmd } func runCopy(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts copyOptions) error { name, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Copy(ctx, name, api.CopyOptions{ Source: opts.source, Destination: opts.destination, All: opts.all, Index: opts.index, FollowLink: opts.followLink, CopyUIDGID: opts.copyUIDGID, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/viz.go
cmd/compose/viz.go
/* Copyright 2023 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 ( "context" "fmt" "os" "strings" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type vizOptions struct { *ProjectOptions includeNetworks bool includePorts bool includeImageName bool indentationStr string } func vizCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := vizOptions{ ProjectOptions: p, } var indentationSize int var useSpaces bool cmd := &cobra.Command{ Use: "viz [OPTIONS]", Short: "EXPERIMENTAL - Generate a graphviz graph from your compose file", PreRunE: Adapt(func(ctx context.Context, args []string) error { var err error opts.indentationStr, err = preferredIndentationStr(indentationSize, useSpaces) return err }), RunE: Adapt(func(ctx context.Context, args []string) error { return runViz(ctx, dockerCli, backendOptions, &opts) }), } cmd.Flags().BoolVar(&opts.includePorts, "ports", false, "Include service's exposed ports in output graph") cmd.Flags().BoolVar(&opts.includeNetworks, "networks", false, "Include service's attached networks in output graph") cmd.Flags().BoolVar(&opts.includeImageName, "image", false, "Include service's image name in output graph") cmd.Flags().IntVar(&indentationSize, "indentation-size", 1, "Number of tabs or spaces to use for indentation") cmd.Flags().BoolVar(&useSpaces, "spaces", false, "If given, space character ' ' will be used to indent,\notherwise tab character '\\t' will be used") return cmd } func runViz(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts *vizOptions) error { _, _ = fmt.Fprintln(os.Stderr, "viz command is EXPERIMENTAL") backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, _, err := opts.ToProject(ctx, dockerCli, backend, nil) if err != nil { return err } // build graph graphStr, _ := backend.Viz(ctx, project, api.VizOptions{ IncludeNetworks: opts.includeNetworks, IncludePorts: opts.includePorts, IncludeImageName: opts.includeImageName, Indentation: opts.indentationStr, }) fmt.Println(graphStr) return nil } // preferredIndentationStr returns a single string given the indentation preference func preferredIndentationStr(size int, useSpace bool) (string, error) { if size < 0 { return "", fmt.Errorf("invalid indentation size: %d", size) } indentationStr := "\t" if useSpace { indentationStr = " " } return strings.Repeat(indentationStr, size), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/pull.go
cmd/compose/pull.go
/* 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 ( "context" "fmt" "os" "github.com/compose-spec/compose-go/v2/cli" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/morikuni/aec" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type pullOptions struct { *ProjectOptions composeOptions quiet bool parallel bool noParallel bool includeDeps bool ignorePullFailures bool noBuildable bool policy string } func pullCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := pullOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "pull [OPTIONS] [SERVICE...]", Short: "Pull service images", PreRunE: func(cmd *cobra.Command, args []string) error { if cmd.Flags().Changed("no-parallel") { fmt.Fprint(os.Stderr, aec.Apply("option '--no-parallel' is DEPRECATED and will be ignored.\n", aec.RedF)) } if cmd.Flags().Changed("parallel") { fmt.Fprint(os.Stderr, aec.Apply("option '--parallel' is DEPRECATED and will be ignored.\n", aec.RedF)) } return nil }, RunE: Adapt(func(ctx context.Context, args []string) error { return runPull(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := cmd.Flags() flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Pull without printing progress information") cmd.Flags().BoolVar(&opts.includeDeps, "include-deps", false, "Also pull services declared as dependencies") cmd.Flags().BoolVar(&opts.parallel, "parallel", true, "DEPRECATED pull multiple images in parallel") flags.MarkHidden("parallel") //nolint:errcheck cmd.Flags().BoolVar(&opts.noParallel, "no-parallel", true, "DEPRECATED disable parallel pulling") flags.MarkHidden("no-parallel") //nolint:errcheck cmd.Flags().BoolVar(&opts.ignorePullFailures, "ignore-pull-failures", false, "Pull what it can and ignores images with pull failures") cmd.Flags().BoolVar(&opts.noBuildable, "ignore-buildable", false, "Ignore images that can be built") cmd.Flags().StringVar(&opts.policy, "policy", "", `Apply pull policy ("missing"|"always")`) return cmd } func (opts pullOptions) apply(project *types.Project, services []string) (*types.Project, error) { if !opts.includeDeps { var err error project, err = project.WithSelectedServices(services, types.IgnoreDependencies) if err != nil { return nil, err } } if opts.policy != "" { for i, service := range project.Services { if service.Image == "" { continue } service.PullPolicy = opts.policy project.Services[i] = service } } return project, nil } func runPull(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts pullOptions, services []string) error { backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, _, err := opts.ToProject(ctx, dockerCli, backend, services, cli.WithoutEnvironmentResolution) if err != nil { return err } project, err = opts.apply(project, services) if err != nil { return err } return backend.Pull(ctx, project, api.PullOptions{ Quiet: opts.quiet, IgnoreFailures: opts.ignorePullFailures, IgnoreBuildable: opts.noBuildable, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/version.go
cmd/compose/version.go
/* 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" "strings" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/internal" ) type versionOptions struct { format string short bool } func versionCommand(dockerCli command.Cli) *cobra.Command { opts := versionOptions{} cmd := &cobra.Command{ Use: "version [OPTIONS]", Short: "Show the Docker Compose version information", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { runVersion(opts, dockerCli) return nil }, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { // overwrite parent PersistentPreRunE to avoid trying to load // compose file on version command if COMPOSE_FILE is set return nil }, } // define flags for backward compatibility with com.docker.cli flags := cmd.Flags() flags.StringVarP(&opts.format, "format", "f", "", "Format the output. Values: [pretty | json]. (Default: pretty)") flags.BoolVar(&opts.short, "short", false, "Shows only Compose's version number") return cmd } func runVersion(opts versionOptions, dockerCli command.Cli) { if opts.short { _, _ = fmt.Fprintln(dockerCli.Out(), strings.TrimPrefix(internal.Version, "v")) return } if opts.format == formatter.JSON { _, _ = fmt.Fprintf(dockerCli.Out(), "{\"version\":%q}\n", internal.Version) return } _, _ = fmt.Fprintln(dockerCli.Out(), "Docker Compose version", internal.Version) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/alpha.go
cmd/compose/alpha.go
/* 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/cli/cli/command" "github.com/spf13/cobra" ) // alphaCommand groups all experimental subcommands func alphaCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { cmd := &cobra.Command{ Short: "Experimental commands", Use: "alpha [COMMAND]", Hidden: true, Annotations: map[string]string{ "experimentalCLI": "true", }, } cmd.AddCommand( vizCommand(p, dockerCli, backendOptions), publishCommand(p, dockerCli, backendOptions), generateCommand(p, dockerCli, backendOptions), ) return cmd }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/events.go
cmd/compose/events.go
/* 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 ( "context" "encoding/json" "fmt" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type eventsOpts struct { *composeOptions json bool since string until string } func eventsCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := eventsOpts{ composeOptions: &composeOptions{ ProjectOptions: p, }, } cmd := &cobra.Command{ Use: "events [OPTIONS] [SERVICE...]", Short: "Receive real time events from containers", RunE: Adapt(func(ctx context.Context, args []string) error { return runEvents(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } cmd.Flags().BoolVar(&opts.json, "json", false, "Output events as a stream of json objects") cmd.Flags().StringVar(&opts.since, "since", "", "Show all events created since timestamp") cmd.Flags().StringVar(&opts.until, "until", "", "Stream events until this timestamp") return cmd } func runEvents(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts eventsOpts, services []string) error { name, err := opts.toProjectName(ctx, dockerCli) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Events(ctx, name, api.EventsOptions{ Services: services, Since: opts.since, Until: opts.until, Consumer: func(event api.Event) error { if opts.json { marshal, err := json.Marshal(map[string]any{ "time": event.Timestamp, "type": "container", "service": event.Service, "id": event.Container, "action": event.Status, "attributes": event.Attributes, }) if err != nil { return err } _, _ = fmt.Fprintln(dockerCli.Out(), string(marshal)) } else { _, _ = fmt.Fprintln(dockerCli.Out(), event) } return nil }, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/generate.go
cmd/compose/generate.go
/* Copyright 2023 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 ( "context" "fmt" "os" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type generateOptions struct { *ProjectOptions Format string } func generateCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := generateOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "generate [OPTIONS] [CONTAINERS...]", Short: "EXPERIMENTAL - Generate a Compose file from existing containers", PreRunE: Adapt(func(ctx context.Context, args []string) error { return nil }), RunE: Adapt(func(ctx context.Context, args []string) error { return runGenerate(ctx, dockerCli, backendOptions, opts, args) }), } cmd.Flags().StringVar(&opts.ProjectName, "name", "", "Project name to set in the Compose file") cmd.Flags().StringVar(&opts.ProjectDir, "project-dir", "", "Directory to use for the project") cmd.Flags().StringVar(&opts.Format, "format", "yaml", "Format the output. Values: [yaml | json]") return cmd } func runGenerate(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts generateOptions, containers []string) error { _, _ = fmt.Fprintln(os.Stderr, "generate command is EXPERIMENTAL") if len(containers) == 0 { return fmt.Errorf("at least one container must be specified") } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, err := backend.Generate(ctx, api.GenerateOptions{ Containers: containers, ProjectName: opts.ProjectName, }) if err != nil { return err } var content []byte switch opts.Format { case "json": content, err = project.MarshalJSON() case "yaml": content, err = project.MarshalYAML() default: return fmt.Errorf("unsupported format %q", opts.Format) } if err != nil { return err } fmt.Println(string(content)) return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/viz_test.go
cmd/compose/viz_test.go
/* 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 ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestPreferredIndentationStr(t *testing.T) { type args struct { size int useSpace bool } tests := []struct { name string args args want string wantErr bool }{ { name: "should return '\\t\\t'", args: args{ size: 2, useSpace: false, }, want: "\t\t", wantErr: false, }, { name: "should return ' '", args: args{ size: 4, useSpace: true, }, want: " ", wantErr: false, }, { name: "should return ''", args: args{ size: 0, useSpace: false, }, want: "", wantErr: false, }, { name: "should return ''", args: args{ size: 0, useSpace: true, }, want: "", wantErr: false, }, { name: "should throw error because indentation size < 0", args: args{ size: -1, useSpace: false, }, want: "", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := preferredIndentationStr(tt.args.size, tt.args.useSpace) if tt.wantErr { require.Errorf(t, err, "preferredIndentationStr(%v, %v)", tt.args.size, tt.args.useSpace) } else { require.NoError(t, err) assert.Equalf(t, tt.want, got, "preferredIndentationStr(%v, %v)", tt.args.size, tt.args.useSpace) } }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/remove.go
cmd/compose/remove.go
/* 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 ( "context" "errors" "fmt" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type removeOptions struct { *ProjectOptions force bool stop bool volumes bool } func removeCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := removeOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "rm [OPTIONS] [SERVICE...]", Short: "Removes stopped service containers", Long: `Removes stopped service containers By default, anonymous volumes attached to containers will not be removed. You can override this with -v. To list all volumes, use "docker volume ls". Any data which is not in a volume will be lost.`, RunE: Adapt(func(ctx context.Context, args []string) error { return runRemove(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } f := cmd.Flags() f.BoolVarP(&opts.force, "force", "f", false, "Don't ask to confirm removal") f.BoolVarP(&opts.stop, "stop", "s", false, "Stop the containers, if required, before removing") f.BoolVarP(&opts.volumes, "volumes", "v", false, "Remove any anonymous volumes attached to containers") f.BoolP("all", "a", false, "Deprecated - no effect") f.MarkHidden("all") //nolint:errcheck return cmd } func runRemove(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts removeOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } err = backend.Remove(ctx, name, api.RemoveOptions{ Services: services, Force: opts.force, Volumes: opts.volumes, Project: project, Stop: opts.stop, }) if errors.Is(err, api.ErrNoResources) { _, _ = fmt.Fprintln(stdinfo(dockerCli), "No stopped containers") return nil } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/up.go
cmd/compose/up.go
/* 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 ( "context" "errors" "fmt" "os" "strings" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" xprogress "github.com/moby/buildkit/util/progress/progressui" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/docker/compose/v5/cmd/display" "github.com/docker/compose/v5/cmd/formatter" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" "github.com/docker/compose/v5/pkg/utils" ) // composeOptions hold options common to `up` and `run` to run compose project type composeOptions struct { *ProjectOptions } type upOptions struct { *composeOptions Detach bool noStart bool noDeps bool cascadeStop bool cascadeFail bool exitCodeFrom string noColor bool noPrefix bool attachDependencies bool attach []string noAttach []string timestamp bool wait bool waitTimeout int watch bool navigationMenu bool navigationMenuChanged bool } func (opts upOptions) apply(project *types.Project, services []string) (*types.Project, error) { if opts.noDeps { var err error project, err = project.WithSelectedServices(services, types.IgnoreDependencies) if err != nil { return nil, err } } if opts.exitCodeFrom != "" { _, err := project.GetService(opts.exitCodeFrom) if err != nil { return nil, err } } return project, nil } func (opts *upOptions) validateNavigationMenu(dockerCli command.Cli) { if !dockerCli.Out().IsTerminal() { opts.navigationMenu = false return } // If --menu flag was not set if !opts.navigationMenuChanged { if envVar, ok := os.LookupEnv(ComposeMenu); ok { opts.navigationMenu = utils.StringToBool(envVar) return } // ...and COMPOSE_MENU env var is not defined we want the default value to be true opts.navigationMenu = true } } func (opts upOptions) OnExit() api.Cascade { switch { case opts.cascadeStop: return api.CascadeStop case opts.cascadeFail: return api.CascadeFail default: return api.CascadeIgnore } } func upCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { up := upOptions{} create := createOptions{} build := buildOptions{ProjectOptions: p} upCmd := &cobra.Command{ Use: "up [OPTIONS] [SERVICE...]", Short: "Create and start containers", PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error { create.pullChanged = cmd.Flags().Changed("pull") create.timeChanged = cmd.Flags().Changed("timeout") up.navigationMenuChanged = cmd.Flags().Changed("menu") if !cmd.Flags().Changed("remove-orphans") { create.removeOrphans = utils.StringToBool(os.Getenv(ComposeRemoveOrphans)) } return validateFlags(&up, &create) }), RunE: p.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error { create.ignoreOrphans = utils.StringToBool(project.Environment[ComposeIgnoreOrphans]) if create.ignoreOrphans && create.removeOrphans { return fmt.Errorf("cannot combine %s and --remove-orphans", ComposeIgnoreOrphans) } if len(up.attach) != 0 && up.attachDependencies { return errors.New("cannot combine --attach and --attach-dependencies") } up.validateNavigationMenu(dockerCli) if !p.All && len(project.Services) == 0 { return fmt.Errorf("no service selected") } return runUp(ctx, dockerCli, backendOptions, create, up, build, project, services) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } flags := upCmd.Flags() flags.BoolVarP(&up.Detach, "detach", "d", false, "Detached mode: Run containers in the background") flags.BoolVar(&create.Build, "build", false, "Build images before starting containers") flags.BoolVar(&create.noBuild, "no-build", false, "Don't build an image, even if it's policy") flags.StringVar(&create.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never")`) flags.BoolVar(&create.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file") flags.StringArrayVar(&create.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.") flags.BoolVar(&up.noColor, "no-color", false, "Produce monochrome output") flags.BoolVar(&up.noPrefix, "no-log-prefix", false, "Don't print prefix in logs") flags.BoolVar(&create.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed") flags.BoolVar(&create.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.") flags.BoolVar(&up.noStart, "no-start", false, "Don't start the services after creating them") flags.BoolVar(&up.cascadeStop, "abort-on-container-exit", false, "Stops all containers if any container was stopped. Incompatible with -d") flags.BoolVar(&up.cascadeFail, "abort-on-container-failure", false, "Stops all containers if any container exited with failure. Incompatible with -d") flags.StringVar(&up.exitCodeFrom, "exit-code-from", "", "Return the exit code of the selected service container. Implies --abort-on-container-exit") flags.IntVarP(&create.timeout, "timeout", "t", 0, "Use this timeout in seconds for container shutdown when attached or when containers are already running") flags.BoolVar(&up.timestamp, "timestamps", false, "Show timestamps") flags.BoolVar(&up.noDeps, "no-deps", false, "Don't start linked services") flags.BoolVar(&create.recreateDeps, "always-recreate-deps", false, "Recreate dependent containers. Incompatible with --no-recreate.") flags.BoolVarP(&create.noInherit, "renew-anon-volumes", "V", false, "Recreate anonymous volumes instead of retrieving data from the previous containers") flags.BoolVar(&create.quietPull, "quiet-pull", false, "Pull without printing progress information") flags.BoolVar(&build.quiet, "quiet-build", false, "Suppress the build output") flags.StringArrayVar(&up.attach, "attach", []string{}, "Restrict attaching to the specified services. Incompatible with --attach-dependencies.") flags.StringArrayVar(&up.noAttach, "no-attach", []string{}, "Do not attach (stream logs) to the specified services") flags.BoolVar(&up.attachDependencies, "attach-dependencies", false, "Automatically attach to log output of dependent services") flags.BoolVar(&up.wait, "wait", false, "Wait for services to be running|healthy. Implies detached mode.") flags.IntVar(&up.waitTimeout, "wait-timeout", 0, "Maximum duration in seconds to wait for the project to be running|healthy") flags.BoolVarP(&up.watch, "watch", "w", false, "Watch source code and rebuild/refresh containers when files are updated.") flags.BoolVar(&up.navigationMenu, "menu", false, "Enable interactive shortcuts when running attached. Incompatible with --detach. Can also be enable/disable by setting COMPOSE_MENU environment var.") flags.BoolVarP(&create.AssumeYes, "yes", "y", false, `Assume "yes" as answer to all prompts and run non-interactively`) flags.SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName { // assumeYes was introduced by mistake as `--y` if name == "y" { logrus.Warn("--y is deprecated, please use --yes instead") name = "yes" } return pflag.NormalizedName(name) }) return upCmd } //nolint:gocyclo func validateFlags(up *upOptions, create *createOptions) error { if up.waitTimeout < 0 { return fmt.Errorf("--wait-timeout must be a non-negative integer") } if up.exitCodeFrom != "" && !up.cascadeFail { up.cascadeStop = true } if up.cascadeStop && up.cascadeFail { return fmt.Errorf("--abort-on-container-failure cannot be combined with --abort-on-container-exit") } if up.wait { if up.attachDependencies || up.cascadeStop || len(up.attach) > 0 { return fmt.Errorf("--wait cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies") } up.Detach = true } if create.Build && create.noBuild { return fmt.Errorf("--build and --no-build are incompatible") } if up.Detach && (up.attachDependencies || up.cascadeStop || up.cascadeFail || len(up.attach) > 0 || up.watch) { if up.wait { return fmt.Errorf("--wait cannot be combined with --abort-on-container-exit, --abort-on-container-failure, --attach, --attach-dependencies or --watch") } else { return fmt.Errorf("--detach cannot be combined with --abort-on-container-exit, --abort-on-container-failure, --attach, --attach-dependencies or --watch") } } if create.noInherit && create.noRecreate { return fmt.Errorf("--no-recreate and --renew-anon-volumes are incompatible") } if create.forceRecreate && create.noRecreate { return fmt.Errorf("--force-recreate and --no-recreate are incompatible") } if create.recreateDeps && create.noRecreate { return fmt.Errorf("--always-recreate-deps and --no-recreate are incompatible") } if create.noBuild && up.watch { return fmt.Errorf("--no-build and --watch are incompatible") } return nil } //nolint:gocyclo func runUp( ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, createOptions createOptions, upOptions upOptions, buildOptions buildOptions, project *types.Project, services []string, ) error { if err := checksForRemoteStack(ctx, dockerCli, project, buildOptions, createOptions.AssumeYes, []string{}); err != nil { return err } err := createOptions.Apply(project) if err != nil { return err } project, err = upOptions.apply(project, services) if err != nil { return err } var build *api.BuildOptions if !createOptions.noBuild { if createOptions.quietPull { buildOptions.Progress = string(xprogress.QuietMode) } // BuildOptions here is nested inside CreateOptions, so // no service list is passed, it will implicitly pick all // services being created, which includes any explicitly // specified via "services" arg here as well as deps bo, err := buildOptions.toAPIBuildOptions(nil) if err != nil { return err } bo.Services = project.ServiceNames() bo.Deps = !upOptions.noDeps build = &bo } create := api.CreateOptions{ Build: build, Services: services, RemoveOrphans: createOptions.removeOrphans, IgnoreOrphans: createOptions.ignoreOrphans, Recreate: createOptions.recreateStrategy(), RecreateDependencies: createOptions.dependenciesRecreateStrategy(), Inherit: !createOptions.noInherit, Timeout: createOptions.GetTimeout(), QuietPull: createOptions.quietPull, } if createOptions.AssumeYes { backendOptions.Options = append(backendOptions.Options, compose.WithPrompt(compose.AlwaysOkPrompt())) } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } if upOptions.noStart { return backend.Create(ctx, project, create) } var consumer api.LogConsumer var attach []string if !upOptions.Detach { consumer = formatter.NewLogConsumer(ctx, dockerCli.Out(), dockerCli.Err(), !upOptions.noColor, !upOptions.noPrefix, upOptions.timestamp) var attachSet utils.Set[string] if len(upOptions.attach) != 0 { // services are passed explicitly with --attach, verify they're valid and then use them as-is attachSet = utils.NewSet(upOptions.attach...) unexpectedSvcs := attachSet.Diff(utils.NewSet(project.ServiceNames()...)) if len(unexpectedSvcs) != 0 { return fmt.Errorf("cannot attach to services not included in up: %s", strings.Join(unexpectedSvcs.Elements(), ", ")) } } else { // mark services being launched (and potentially their deps) for attach // if they didn't opt-out via Compose YAML attachSet = utils.NewSet[string]() var dependencyOpt types.DependencyOption = types.IgnoreDependencies if upOptions.attachDependencies { dependencyOpt = types.IncludeDependencies } if err := project.ForEachService(services, func(serviceName string, s *types.ServiceConfig) error { if s.Attach == nil || *s.Attach { attachSet.Add(serviceName) } return nil }, dependencyOpt); err != nil { return err } } // filter out any services that have been explicitly marked for ignore with `--no-attach` attachSet.RemoveAll(upOptions.noAttach...) attach = attachSet.Elements() } var timeout time.Duration if upOptions.waitTimeout > 0 { timeout = time.Duration(upOptions.waitTimeout) * time.Second } return backend.Up(ctx, project, api.UpOptions{ Create: create, Start: api.StartOptions{ Project: project, Attach: consumer, AttachTo: attach, ExitCodeFrom: upOptions.exitCodeFrom, OnExit: upOptions.OnExit(), Wait: upOptions.wait, WaitTimeout: timeout, Watch: upOptions.watch, Services: services, NavigationMenu: upOptions.navigationMenu && display.Mode != "plain" && dockerCli.In().IsTerminal(), }, }) } func setServiceScale(project *types.Project, name string, replicas int) error { service, err := project.GetService(name) if err != nil { return err } service.SetScale(replicas) project.Services[name] = service return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/pause.go
cmd/compose/pause.go
/* 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 ( "context" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type pauseOptions struct { *ProjectOptions } func pauseCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := pauseOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "pause [SERVICE...]", Short: "Pause services", RunE: Adapt(func(ctx context.Context, args []string) error { return runPause(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } return cmd } func runPause(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts pauseOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.Pause(ctx, name, api.PauseOptions{ Services: services, Project: project, }) } type unpauseOptions struct { *ProjectOptions } func unpauseCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := unpauseOptions{ ProjectOptions: p, } cmd := &cobra.Command{ Use: "unpause [SERVICE...]", Short: "Unpause services", RunE: Adapt(func(ctx context.Context, args []string) error { return runUnPause(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } return cmd } func runUnPause(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts unpauseOptions, services []string) error { project, name, err := opts.projectOrName(ctx, dockerCli, services...) if err != nil { return err } backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } return backend.UnPause(ctx, name, api.PauseOptions{ Services: services, Project: project, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/push.go
cmd/compose/push.go
/* 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 ( "context" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/pkg/api" "github.com/docker/compose/v5/pkg/compose" ) type pushOptions struct { *ProjectOptions composeOptions IncludeDeps bool Ignorefailures bool Quiet bool } func pushCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command { opts := pushOptions{ ProjectOptions: p, } pushCmd := &cobra.Command{ Use: "push [OPTIONS] [SERVICE...]", Short: "Push service images", RunE: Adapt(func(ctx context.Context, args []string) error { return runPush(ctx, dockerCli, backendOptions, opts, args) }), ValidArgsFunction: completeServiceNames(dockerCli, p), } pushCmd.Flags().BoolVar(&opts.Ignorefailures, "ignore-push-failures", false, "Push what it can and ignores images with push failures") pushCmd.Flags().BoolVar(&opts.IncludeDeps, "include-deps", false, "Also push images of services declared as dependencies") pushCmd.Flags().BoolVarP(&opts.Quiet, "quiet", "q", false, "Push without printing progress information") return pushCmd } func runPush(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts pushOptions, services []string) error { backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...) if err != nil { return err } project, _, err := opts.ToProject(ctx, dockerCli, backend, services) if err != nil { return err } if !opts.IncludeDeps { project, err = project.WithSelectedServices(services, types.IgnoreDependencies) if err != nil { return err } } return backend.Push(ctx, project, api.PushOptions{ IgnoreFailures: opts.Ignorefailures, Quiet: opts.Quiet, }) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compose/up_test.go
cmd/compose/up_test.go
/* 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 ( "testing" "github.com/compose-spec/compose-go/v2/types" "gotest.tools/v3/assert" "github.com/docker/compose/v5/pkg/api" ) func TestApplyScaleOpt(t *testing.T) { p := types.Project{ Services: types.Services{ "foo": { Name: "foo", }, "bar": { Name: "bar", Deploy: &types.DeployConfig{ Mode: "test", }, }, }, } err := applyScaleOpts(&p, []string{"foo=2", "bar=3"}) assert.NilError(t, err) foo, err := p.GetService("foo") assert.NilError(t, err) assert.Equal(t, *foo.Scale, 2) bar, err := p.GetService("bar") assert.NilError(t, err) assert.Equal(t, *bar.Scale, 3) assert.Equal(t, *bar.Deploy.Replicas, 3) } func TestUpOptions_OnExit(t *testing.T) { tests := []struct { name string args upOptions want api.Cascade }{ { name: "no cascade", args: upOptions{}, want: api.CascadeIgnore, }, { name: "cascade stop", args: upOptions{cascadeStop: true}, want: api.CascadeStop, }, { name: "cascade fail", args: upOptions{cascadeFail: true}, want: api.CascadeFail, }, { name: "both set - stop takes precedence", args: upOptions{ cascadeStop: true, cascadeFail: true, }, want: api.CascadeStop, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := tt.args.OnExit() assert.Equal(t, got, tt.want) }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compatibility/convert_test.go
cmd/compatibility/convert_test.go
/* 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 compatibility import ( "errors" "os" "os/exec" "testing" "gotest.tools/v3/assert" ) func Test_convert(t *testing.T) { tests := []struct { name string args []string want []string wantErr bool }{ { name: "compose only", args: []string{"up"}, want: []string{"compose", "up"}, }, { name: "with context", args: []string{"--context", "foo", "-f", "compose.yaml", "up"}, want: []string{"--context", "foo", "compose", "-f", "compose.yaml", "up"}, }, { name: "with context arg", args: []string{"--context=foo", "-f", "compose.yaml", "up"}, want: []string{"--context", "foo", "compose", "-f", "compose.yaml", "up"}, }, { name: "with host", args: []string{"--host", "tcp://1.2.3.4", "up"}, want: []string{"--host", "tcp://1.2.3.4", "compose", "up"}, }, { name: "compose --verbose", args: []string{"--verbose"}, want: []string{"--debug", "compose"}, }, { name: "compose --version", args: []string{"--version"}, want: []string{"compose", "version"}, }, { name: "compose -v", args: []string{"-v"}, want: []string{"compose", "version"}, }, { name: "help", args: []string{"-h"}, want: []string{"compose", "--help"}, }, { name: "issues/1962", args: []string{"psql", "-h", "postgres"}, want: []string{"compose", "psql", "-h", "postgres"}, // -h should not be converted to --help }, { name: "issues/8648", args: []string{"exec", "mongo", "mongo", "--host", "mongo"}, want: []string{"compose", "exec", "mongo", "mongo", "--host", "mongo"}, // --host is passed to exec }, { name: "issues/12", args: []string{"--log-level", "INFO", "up"}, want: []string{"--log-level", "INFO", "compose", "up"}, }, { name: "empty string argument", args: []string{"--project-directory", "", "ps"}, want: []string{"compose", "--project-directory", "", "ps"}, }, { name: "compose as project name", args: []string{"--project-name", "compose", "down", "--remove-orphans"}, want: []string{"compose", "--project-name", "compose", "down", "--remove-orphans"}, }, { name: "completion command", args: []string{"__complete", "up"}, want: []string{"__complete", "compose", "up"}, }, { name: "string flag without argument", args: []string{"--log-level"}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.wantErr { if os.Getenv("BE_CRASHER") == "1" { Convert(tt.args) return } cmd := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$") cmd.Env = append(os.Environ(), "BE_CRASHER=1") err := cmd.Run() var e *exec.ExitError if errors.As(err, &e) && !e.Success() { return } t.Fatalf("process ran with err %v, want exit status 1", err) } else { got := Convert(tt.args) assert.DeepEqual(t, tt.want, got) } }) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/cmd/compatibility/convert.go
cmd/compatibility/convert.go
/* 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 compatibility import ( "fmt" "os" "strings" "github.com/docker/compose/v5/cmd/compose" ) func getCompletionCommands() []string { return []string{ "__complete", "__completeNoDesc", } } func getBoolFlags() []string { return []string{ "--debug", "-D", "--verbose", "--tls", "--tlsverify", } } func getStringFlags() []string { return []string{ "--tlscacert", "--tlscert", "--tlskey", "--host", "-H", "--context", "--log-level", } } // Convert transforms standalone docker-compose args into CLI plugin compliant ones func Convert(args []string) []string { var rootFlags []string command := []string{compose.PluginName} l := len(args) ARGS: for i := 0; i < l; i++ { arg := args[i] if contains(getCompletionCommands(), arg) { command = append([]string{arg}, command...) continue } if arg != "" && arg[0] != '-' { command = append(command, args[i:]...) break } switch arg { case "--verbose": arg = "--debug" case "-h": // docker cli has deprecated -h to avoid ambiguity with -H, while docker-compose still support it arg = "--help" case "--version", "-v": // redirect --version pseudo-command to actual command arg = "version" } if contains(getBoolFlags(), arg) { rootFlags = append(rootFlags, arg) continue } for _, flag := range getStringFlags() { if arg == flag { i++ if i >= l { fmt.Fprintf(os.Stderr, "flag needs an argument: '%s'\n", arg) os.Exit(1) } rootFlags = append(rootFlags, arg, args[i]) continue ARGS } if strings.HasPrefix(arg, flag) { _, val, found := strings.Cut(arg, "=") if found { rootFlags = append(rootFlags, flag, val) continue ARGS } } } command = append(command, arg) } return append(rootFlags, command...) } func contains(array []string, needle string) bool { for _, val := range array { if val == needle { return true } } return false }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/docs/yaml/main/generate.go
docs/yaml/main/generate.go
/* 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 main import ( "fmt" "os" "path/filepath" clidocstool "github.com/docker/cli-docs-tool" "github.com/docker/cli/cli/command" "github.com/spf13/cobra" "github.com/docker/compose/v5/cmd/compose" ) func generateDocs(opts *options) error { dockerCLI, err := command.NewDockerCli() if err != nil { return err } cmd := &cobra.Command{ Use: "docker", DisableAutoGenTag: true, } cmd.AddCommand(compose.RootCommand(dockerCLI, nil)) disableFlagsInUseLine(cmd) tool, err := clidocstool.New(clidocstool.Options{ Root: cmd, SourceDir: opts.source, TargetDir: opts.target, Plugin: true, }) if err != nil { return err } for _, format := range opts.formats { switch format { case "yaml": if err := tool.GenYamlTree(cmd); err != nil { return err } case "md": if err := tool.GenMarkdownTree(cmd); err != nil { return err } default: return fmt.Errorf("unknown format %q", format) } } return nil } func disableFlagsInUseLine(cmd *cobra.Command) { visitAll(cmd, func(ccmd *cobra.Command) { // do not add a `[flags]` to the end of the usage line. ccmd.DisableFlagsInUseLine = true }) } // visitAll will traverse all commands from the root. // This is different from the VisitAll of cobra.Command where only parents // are checked. func visitAll(root *cobra.Command, fn func(*cobra.Command)) { for _, cmd := range root.Commands() { visitAll(cmd, fn) } fn(root) } type options struct { source string target string formats []string } func main() { cwd, _ := os.Getwd() opts := &options{ source: filepath.Join(cwd, "docs", "reference"), target: filepath.Join(cwd, "docs", "reference"), formats: []string{"yaml", "md"}, } fmt.Printf("Project root: %s\n", opts.source) fmt.Printf("Generating yaml files into %s\n", opts.target) if err := generateDocs(opts); err != nil { _, _ = fmt.Fprintf(os.Stderr, "Failed to generate documentation: %s\n", err.Error()) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/docs/examples/provider.go
docs/examples/provider.go
/* 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 main import ( "encoding/json" "fmt" "os" "time" "github.com/spf13/cobra" "github.com/spf13/pflag" ) func main() { cmd := &cobra.Command{ Short: "Compose Provider Example", Use: "demo", } cmd.AddCommand(composeCommand()) err := cmd.Execute() if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } type options struct { db string size int } func composeCommand() *cobra.Command { c := &cobra.Command{ Use: "compose EVENT", TraverseChildren: true, } c.PersistentFlags().String("project-name", "", "compose project name") // unused var options options upCmd := &cobra.Command{ Use: "up", Run: func(_ *cobra.Command, args []string) { up(options, args) }, Args: cobra.ExactArgs(1), } upCmd.Flags().StringVar(&options.db, "type", "", "Database type (mysql, postgres, etc.)") _ = upCmd.MarkFlagRequired("type") upCmd.Flags().IntVar(&options.size, "size", 10, "Database size in GB") upCmd.Flags().String("name", "", "Name of the database to be created") _ = upCmd.MarkFlagRequired("name") downCmd := &cobra.Command{ Use: "down", Run: down, Args: cobra.ExactArgs(1), } downCmd.Flags().String("name", "", "Name of the database to be deleted") _ = downCmd.MarkFlagRequired("name") c.AddCommand(upCmd, downCmd) c.AddCommand(metadataCommand(upCmd, downCmd)) return c } const lineSeparator = "\n" func up(options options, args []string) { servicename := args[0] fmt.Printf(`{ "type": "debug", "message": "Starting %s" }%s`, servicename, lineSeparator) for i := 0; i < options.size; i += 10 { time.Sleep(1 * time.Second) fmt.Printf(`{ "type": "info", "message": "Processing ... %d%%" }%s`, i*100/options.size, lineSeparator) } fmt.Printf(`{ "type": "setenv", "message": "URL=https://magic.cloud/%s" }%s`, servicename, lineSeparator) } func down(_ *cobra.Command, _ []string) { fmt.Printf(`{ "type": "error", "message": "Permission error" }%s`, lineSeparator) } func metadataCommand(upCmd, downCmd *cobra.Command) *cobra.Command { return &cobra.Command{ Use: "metadata", Run: func(cmd *cobra.Command, _ []string) { metadata(upCmd, downCmd) }, Args: cobra.NoArgs, } } func metadata(upCmd, downCmd *cobra.Command) { metadata := ProviderMetadata{} metadata.Description = "Manage services on AwesomeCloud" metadata.Up = commandParameters(upCmd) metadata.Down = commandParameters(downCmd) jsonMetadata, err := json.Marshal(metadata) if err != nil { panic(err) } fmt.Println(string(jsonMetadata)) } func commandParameters(cmd *cobra.Command) CommandMetadata { cmdMetadata := CommandMetadata{} cmd.Flags().VisitAll(func(f *pflag.Flag) { _, isRequired := f.Annotations[cobra.BashCompOneRequiredFlag] cmdMetadata.Parameters = append(cmdMetadata.Parameters, Metadata{ Name: f.Name, Description: f.Usage, Required: isRequired, Type: f.Value.Type(), Default: f.DefValue, }) }) return cmdMetadata } type ProviderMetadata struct { Description string `json:"description"` Up CommandMetadata `json:"up"` Down CommandMetadata `json:"down"` } type CommandMetadata struct { Parameters []Metadata `json:"parameters"` } type Metadata struct { Name string `json:"name"` Description string `json:"description"` Required bool `json:"required"` Type string `json:"type"` Default string `json:"default,omitempty"` }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/variables.go
internal/variables.go
/* Copyright 2023 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 internal // Version is the version of the CLI injected in compilation time var Version = "dev"
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/attributes_test.go
internal/tracing/attributes_test.go
/* Copyright 2024 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 tracing import ( "testing" "github.com/compose-spec/compose-go/v2/types" "github.com/stretchr/testify/require" ) func TestProjectHash(t *testing.T) { projA := &types.Project{ Name: "fake-proj", WorkingDir: "/tmp", Services: map[string]types.ServiceConfig{ "foo": {Image: "fake-image"}, }, DisabledServices: map[string]types.ServiceConfig{ "bar": {Image: "diff-image"}, }, } projB := &types.Project{ Name: "fake-proj", WorkingDir: "/tmp", Services: map[string]types.ServiceConfig{ "foo": {Image: "fake-image"}, "bar": {Image: "diff-image"}, }, } projC := &types.Project{ Name: "fake-proj", WorkingDir: "/tmp", Services: map[string]types.ServiceConfig{ "foo": {Image: "fake-image"}, "bar": {Image: "diff-image"}, "baz": {Image: "yet-another-image"}, }, } hashA, ok := projectHash(projA) require.True(t, ok) require.NotEmpty(t, hashA) hashB, ok := projectHash(projB) require.True(t, ok) require.NotEmpty(t, hashB) require.Equal(t, hashA, hashB) hashC, ok := projectHash(projC) require.True(t, ok) require.NotEmpty(t, hashC) require.NotEqual(t, hashC, hashA) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/tracing_test.go
internal/tracing/tracing_test.go
/* Copyright 2023 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 tracing_test import ( "testing" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/context/store" "github.com/stretchr/testify/require" "github.com/docker/compose/v5/internal/tracing" ) var testStoreCfg = store.NewConfig( func() any { return &map[string]any{} }, ) func TestExtractOtelFromContext(t *testing.T) { if testing.Short() { t.Skip("Requires filesystem access") } dir := t.TempDir() st := store.New(dir, testStoreCfg) err := st.CreateOrUpdate(store.Metadata{ Name: "test", Metadata: command.DockerContext{ Description: t.Name(), AdditionalFields: map[string]any{ "otel": map[string]any{ "OTEL_EXPORTER_OTLP_ENDPOINT": "localhost:1234", }, }, }, Endpoints: make(map[string]any), }) require.NoError(t, err) cfg, err := tracing.ConfigFromDockerContext(st, "test") require.NoError(t, err) require.Equal(t, "localhost:1234", cfg.Endpoint) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/errors.go
internal/tracing/errors.go
/* Copyright 2023 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 tracing import ( "go.opentelemetry.io/otel" ) // skipErrors is a no-op otel.ErrorHandler. type skipErrors struct{} // Handle does nothing, ignoring any errors passed to it. func (skipErrors) Handle(_ error) {} var _ otel.ErrorHandler = skipErrors{}
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/attributes.go
internal/tracing/attributes.go
/* 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 tracing import ( "context" "crypto/sha256" "encoding/json" "fmt" "strings" "time" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/docker/api/types/container" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" ) // SpanOptions is a small helper type to make it easy to share the options helpers between // downstream functions that accept slices of trace.SpanStartOption and trace.EventOption. type SpanOptions []trace.SpanStartEventOption type MetricsKey struct{} type Metrics struct { CountExtends int CountIncludesLocal int CountIncludesRemote int } func (s SpanOptions) SpanStartOptions() []trace.SpanStartOption { out := make([]trace.SpanStartOption, len(s)) for i := range s { out[i] = s[i] } return out } func (s SpanOptions) EventOptions() []trace.EventOption { out := make([]trace.EventOption, len(s)) for i := range s { out[i] = s[i] } return out } // ProjectOptions returns common attributes from a Compose project. // // For convenience, it's returned as a SpanOptions object to allow it to be // passed directly to the wrapping helper methods in this package such as // SpanWrapFunc. func ProjectOptions(ctx context.Context, proj *types.Project) SpanOptions { if proj == nil { return nil } capabilities, gpu, tpu := proj.ServicesWithCapabilities() attrs := []attribute.KeyValue{ attribute.String("project.name", proj.Name), attribute.String("project.dir", proj.WorkingDir), attribute.StringSlice("project.compose_files", proj.ComposeFiles), attribute.StringSlice("project.profiles", proj.Profiles), attribute.StringSlice("project.volumes", proj.VolumeNames()), attribute.StringSlice("project.networks", proj.NetworkNames()), attribute.StringSlice("project.secrets", proj.SecretNames()), attribute.StringSlice("project.configs", proj.ConfigNames()), attribute.StringSlice("project.models", proj.ModelNames()), attribute.StringSlice("project.extensions", keys(proj.Extensions)), attribute.StringSlice("project.services.active", proj.ServiceNames()), attribute.StringSlice("project.services.disabled", proj.DisabledServiceNames()), attribute.StringSlice("project.services.build", proj.ServicesWithBuild()), attribute.StringSlice("project.services.depends_on", proj.ServicesWithDependsOn()), attribute.StringSlice("project.services.models", proj.ServicesWithModels()), attribute.StringSlice("project.services.capabilities", capabilities), attribute.StringSlice("project.services.capabilities.gpu", gpu), attribute.StringSlice("project.services.capabilities.tpu", tpu), } if metrics, ok := ctx.Value(MetricsKey{}).(Metrics); ok { attrs = append(attrs, attribute.Int("project.services.extends", metrics.CountExtends)) attrs = append(attrs, attribute.Int("project.includes.local", metrics.CountIncludesLocal)) attrs = append(attrs, attribute.Int("project.includes.remote", metrics.CountIncludesRemote)) } if projHash, ok := projectHash(proj); ok { attrs = append(attrs, attribute.String("project.hash", projHash)) } return []trace.SpanStartEventOption{ trace.WithAttributes(attrs...), } } // ServiceOptions returns common attributes from a Compose service. // // For convenience, it's returned as a SpanOptions object to allow it to be // passed directly to the wrapping helper methods in this package such as // SpanWrapFunc. func ServiceOptions(service types.ServiceConfig) SpanOptions { attrs := []attribute.KeyValue{ attribute.String("service.name", service.Name), attribute.String("service.image", service.Image), attribute.StringSlice("service.networks", keys(service.Networks)), attribute.StringSlice("service.models", keys(service.Models)), } configNames := make([]string, len(service.Configs)) for i := range service.Configs { configNames[i] = service.Configs[i].Source } attrs = append(attrs, attribute.StringSlice("service.configs", configNames)) secretNames := make([]string, len(service.Secrets)) for i := range service.Secrets { secretNames[i] = service.Secrets[i].Source } attrs = append(attrs, attribute.StringSlice("service.secrets", secretNames)) volNames := make([]string, len(service.Volumes)) for i := range service.Volumes { volNames[i] = service.Volumes[i].Source } attrs = append(attrs, attribute.StringSlice("service.volumes", volNames)) return []trace.SpanStartEventOption{ trace.WithAttributes(attrs...), } } // ContainerOptions returns common attributes from a Moby container. // // For convenience, it's returned as a SpanOptions object to allow it to be // passed directly to the wrapping helper methods in this package such as // SpanWrapFunc. func ContainerOptions(ctr container.Summary) SpanOptions { attrs := []attribute.KeyValue{ attribute.String("container.id", ctr.ID), attribute.String("container.image", ctr.Image), unixTimeAttr("container.created_at", ctr.Created), } if len(ctr.Names) != 0 { attrs = append(attrs, attribute.String("container.name", strings.TrimPrefix(ctr.Names[0], "/"))) } return []trace.SpanStartEventOption{ trace.WithAttributes(attrs...), } } func keys[T any](m map[string]T) []string { out := make([]string, 0, len(m)) for k := range m { out = append(out, k) } return out } func timeAttr(key string, value time.Time) attribute.KeyValue { return attribute.String(key, value.Format(time.RFC3339)) } func unixTimeAttr(key string, value int64) attribute.KeyValue { return timeAttr(key, time.Unix(value, 0).UTC()) } // projectHash returns a checksum from the JSON encoding of the project. func projectHash(p *types.Project) (string, bool) { if p == nil { return "", false } // disabled services aren't included in the output, so make a copy with // all the services active for hashing var err error p, err = p.WithServicesEnabled(append(p.ServiceNames(), p.DisabledServiceNames()...)...) if err != nil { return "", false } projData, err := json.Marshal(p) if err != nil { return "", false } d := sha256.Sum256(projData) return fmt.Sprintf("%x", d), true }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/docker_context.go
internal/tracing/docker_context.go
/* Copyright 2023 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 tracing import ( "fmt" "os" "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/context/store" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/docker/compose/v5/internal/memnet" ) const otelConfigFieldName = "otel" // traceClientFromDockerContext creates a gRPC OTLP client based on metadata // from the active Docker CLI context. func traceClientFromDockerContext(dockerCli command.Cli, otelEnv envMap) (otlptrace.Client, error) { // attempt to extract an OTEL config from the Docker context to enable // automatic integration with Docker Desktop; cfg, err := ConfigFromDockerContext(dockerCli.ContextStore(), dockerCli.CurrentContext()) if err != nil { return nil, fmt.Errorf("loading otel config from docker context metadata: %w", err) } if cfg.Endpoint == "" { return nil, nil } // HACK: unfortunately _all_ public OTEL initialization functions // implicitly read from the OS env, so temporarily unset them all and // restore afterwards defer func() { for k, v := range otelEnv { if err := os.Setenv(k, v); err != nil { panic(fmt.Errorf("restoring env for %q: %w", k, err)) } } }() for k := range otelEnv { if err := os.Unsetenv(k); err != nil { return nil, fmt.Errorf("stashing env for %q: %w", k, err) } } conn, err := grpc.NewClient(cfg.Endpoint, grpc.WithContextDialer(memnet.DialEndpoint), // this dial is restricted to using a local Unix socket / named pipe, // so there is no need for TLS grpc.WithTransportCredentials(insecure.NewCredentials()), ) if err != nil { return nil, fmt.Errorf("initializing otel connection from docker context metadata: %w", err) } client := otlptracegrpc.NewClient(otlptracegrpc.WithGRPCConn(conn)) return client, nil } // ConfigFromDockerContext inspects extra metadata included as part of the // specified Docker context to try and extract a valid OTLP client configuration. func ConfigFromDockerContext(st store.Store, name string) (OTLPConfig, error) { meta, err := st.GetMetadata(name) if err != nil { return OTLPConfig{}, err } var otelCfg any switch m := meta.Metadata.(type) { case command.DockerContext: otelCfg = m.AdditionalFields[otelConfigFieldName] case map[string]any: otelCfg = m[otelConfigFieldName] } if otelCfg == nil { return OTLPConfig{}, nil } otelMap, ok := otelCfg.(map[string]any) if !ok { return OTLPConfig{}, fmt.Errorf( "unexpected type for field %q: %T (expected: %T)", otelConfigFieldName, otelCfg, otelMap, ) } // keys from https://opentelemetry.io/docs/concepts/sdk-configuration/otlp-exporter-configuration/ cfg := OTLPConfig{ Endpoint: valueOrDefault[string](otelMap, "OTEL_EXPORTER_OTLP_ENDPOINT"), } return cfg, nil } // valueOrDefault returns the type-cast value at the specified key in the map // if present and the correct type; otherwise, it returns the default value for // T. func valueOrDefault[T any](m map[string]any, key string) T { if v, ok := m[key].(T); ok { return v } return *new(T) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/tracing.go
internal/tracing/tracing.go
/* 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 tracing import ( "context" "errors" "fmt" "os" "strings" "github.com/docker/cli/cli/command" "github.com/moby/buildkit/util/tracing/detect" _ "github.com/moby/buildkit/util/tracing/env" //nolint:blank-imports "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.21.0" "github.com/docker/compose/v5/internal" ) func init() { detect.ServiceName = "compose" // do not log tracing errors to stdio otel.SetErrorHandler(skipErrors{}) } // OTLPConfig contains the necessary values to initialize an OTLP client // manually. // // This supports a minimal set of options based on what is necessary for // automatic OTEL configuration from Docker context metadata. type OTLPConfig struct { Endpoint string } // ShutdownFunc flushes and stops an OTEL exporter. type ShutdownFunc func(ctx context.Context) error // envMap is a convenience type for OS environment variables. type envMap map[string]string func InitTracing(dockerCli command.Cli) (ShutdownFunc, error) { // set global propagator to tracecontext (the default is no-op). otel.SetTextMapPropagator(propagation.TraceContext{}) return InitProvider(dockerCli) } func InitProvider(dockerCli command.Cli) (ShutdownFunc, error) { ctx := context.Background() var errs []error var exporters []sdktrace.SpanExporter envClient, otelEnv := traceClientFromEnv() if envClient != nil { if envExporter, err := otlptrace.New(ctx, envClient); err != nil { errs = append(errs, err) } else if envExporter != nil { exporters = append(exporters, envExporter) } } if dcClient, err := traceClientFromDockerContext(dockerCli, otelEnv); err != nil { errs = append(errs, err) } else if dcClient != nil { if dcExporter, err := otlptrace.New(ctx, dcClient); err != nil { errs = append(errs, err) } else if dcExporter != nil { exporters = append(exporters, dcExporter) } } if len(errs) != 0 { return nil, errors.Join(errs...) } res, err := resource.New( ctx, resource.WithAttributes( semconv.ServiceName("compose"), semconv.ServiceVersion(internal.Version), attribute.String("docker.context", dockerCli.CurrentContext()), ), ) if err != nil { return nil, fmt.Errorf("failed to create resource: %w", err) } muxExporter := MuxExporter{exporters: exporters} tracerProvider := sdktrace.NewTracerProvider( sdktrace.WithResource(res), sdktrace.WithBatcher(muxExporter), ) otel.SetTracerProvider(tracerProvider) // Shutdown will flush any remaining spans and shut down the exporter. return tracerProvider.Shutdown, nil } // traceClientFromEnv creates a GRPC OTLP client based on OS environment // variables. // // https://opentelemetry.io/docs/concepts/sdk-configuration/otlp-exporter-configuration/ func traceClientFromEnv() (otlptrace.Client, envMap) { hasOtelEndpointInEnv := false otelEnv := make(map[string]string) for _, kv := range os.Environ() { k, v, ok := strings.Cut(kv, "=") if !ok { continue } if strings.HasPrefix(k, "OTEL_") { otelEnv[k] = v if strings.HasSuffix(k, "ENDPOINT") { hasOtelEndpointInEnv = true } } } if !hasOtelEndpointInEnv { return nil, nil } client := otlptracegrpc.NewClient() return client, otelEnv }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/keyboard_metrics.go
internal/tracing/keyboard_metrics.go
/* Copyright 2024 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 tracing import ( "context" "go.opentelemetry.io/otel/attribute" ) func KeyboardMetrics(ctx context.Context, enabled, isDockerDesktopActive bool) { commandAvailable := []string{} if isDockerDesktopActive { commandAvailable = append(commandAvailable, "gui") commandAvailable = append(commandAvailable, "gui/composeview") } AddAttributeToSpan(ctx, attribute.Bool("navmenu.enabled", enabled), attribute.StringSlice("navmenu.command_available", commandAvailable)) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/wrap.go
internal/tracing/wrap.go
/* 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 tracing import ( "context" "github.com/acarl005/stripansi" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" semconv "go.opentelemetry.io/otel/semconv/v1.19.0" "go.opentelemetry.io/otel/trace" ) // SpanWrapFunc wraps a function that takes a context with a trace.Span, marking the status as codes.Error if the // wrapped function returns an error. // // The context passed to the function is created from the span to ensure correct propagation. // // NOTE: This function is nearly identical to SpanWrapFuncForErrGroup, except the latter is designed specially for // convenience with errgroup.Group due to its prevalence throughout the codebase. The code is duplicated to avoid // adding even more levels of function wrapping/indirection. func SpanWrapFunc(spanName string, opts SpanOptions, fn func(ctx context.Context) error) func(context.Context) error { return func(ctx context.Context) error { ctx, span := otel.Tracer("").Start(ctx, spanName, opts.SpanStartOptions()...) defer span.End() if err := fn(ctx); err != nil { span.SetStatus(codes.Error, err.Error()) return err } span.SetStatus(codes.Ok, "") return nil } } // SpanWrapFuncForErrGroup wraps a function that takes a context with a trace.Span, marking the status as codes.Error // if the wrapped function returns an error. // // The context passed to the function is created from the span to ensure correct propagation. // // NOTE: This function is nearly identical to SpanWrapFunc, except this function is designed specially for // convenience with errgroup.Group due to its prevalence throughout the codebase. The code is duplicated to avoid // adding even more levels of function wrapping/indirection. func SpanWrapFuncForErrGroup(ctx context.Context, spanName string, opts SpanOptions, fn func(ctx context.Context) error) func() error { return func() error { ctx, span := otel.Tracer("").Start(ctx, spanName, opts.SpanStartOptions()...) defer span.End() if err := fn(ctx); err != nil { span.SetStatus(codes.Error, err.Error()) return err } span.SetStatus(codes.Ok, "") return nil } } // EventWrapFuncForErrGroup invokes a function and records an event, optionally including the returned // error as the "exception message" on the event. // // This is intended for lightweight usage to wrap errgroup.Group calls where a full span is not desired. func EventWrapFuncForErrGroup(ctx context.Context, eventName string, opts SpanOptions, fn func(ctx context.Context) error) func() error { return func() error { span := trace.SpanFromContext(ctx) eventOpts := opts.EventOptions() err := fn(ctx) if err != nil { eventOpts = append(eventOpts, trace.WithAttributes(semconv.ExceptionMessage(stripansi.Strip(err.Error())))) } span.AddEvent(eventName, eventOpts...) return err } } func AddAttributeToSpan(ctx context.Context, attr ...attribute.KeyValue) { span := trace.SpanFromContext(ctx) span.SetAttributes(attr...) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/tracing/mux.go
internal/tracing/mux.go
/* Copyright 2023 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 tracing import ( "context" "errors" "sync" sdktrace "go.opentelemetry.io/otel/sdk/trace" ) type MuxExporter struct { exporters []sdktrace.SpanExporter } func (m MuxExporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error { var ( wg sync.WaitGroup errMu sync.Mutex errs = make([]error, 0, len(m.exporters)) ) for _, exporter := range m.exporters { wg.Add(1) go func() { defer wg.Done() if err := exporter.ExportSpans(ctx, spans); err != nil { errMu.Lock() errs = append(errs, err) errMu.Unlock() } }() } wg.Wait() return errors.Join(errs...) } func (m MuxExporter) Shutdown(ctx context.Context) error { var ( wg sync.WaitGroup errMu sync.Mutex errs = make([]error, 0, len(m.exporters)) ) for _, exporter := range m.exporters { wg.Add(1) go func() { defer wg.Done() if err := exporter.Shutdown(ctx); err != nil { errMu.Lock() errs = append(errs, err) errMu.Unlock() } }() } wg.Wait() return errors.Join(errs...) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/memnet/conn_unix.go
internal/memnet/conn_unix.go
//go:build !windows /* Copyright 2023 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 memnet import ( "context" "fmt" "net" "syscall" ) const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path) func dialNamedPipe(_ context.Context, _ string) (net.Conn, error) { return nil, fmt.Errorf("named pipes are only available on Windows") } func validateSocketPath(addr string) error { if len(addr) > maxUnixSocketPathSize { return fmt.Errorf("socket address is too long: %s", addr) } return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/memnet/conn.go
internal/memnet/conn.go
/* 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 memnet import ( "context" "fmt" "net" "strings" ) func DialEndpoint(ctx context.Context, endpoint string) (net.Conn, error) { if addr, ok := strings.CutPrefix(endpoint, "unix://"); ok { return Dial(ctx, "unix", addr) } if addr, ok := strings.CutPrefix(endpoint, "npipe://"); ok { return Dial(ctx, "npipe", addr) } return nil, fmt.Errorf("unsupported protocol for address: %s", endpoint) } func Dial(ctx context.Context, network, addr string) (net.Conn, error) { var d net.Dialer switch network { case "unix": if err := validateSocketPath(addr); err != nil { return nil, err } return d.DialContext(ctx, "unix", addr) case "npipe": // N.B. this will return an error on non-Windows return dialNamedPipe(ctx, addr) default: return nil, fmt.Errorf("unsupported network: %s", network) } }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/memnet/conn_windows.go
internal/memnet/conn_windows.go
/* Copyright 2023 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 memnet import ( "context" "net" "github.com/Microsoft/go-winio" ) func dialNamedPipe(ctx context.Context, addr string) (net.Conn, error) { return winio.DialPipeContext(ctx, addr) } func validateSocketPath(addr string) error { // AF_UNIX sockets do not have strict path limits on Windows return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/desktop/client.go
internal/desktop/client.go
/* Copyright 2024 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 desktop import ( "context" "encoding/json" "fmt" "io" "net" "net/http" "strings" "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" "github.com/docker/compose/v5/internal" "github.com/docker/compose/v5/internal/memnet" ) // identify this client in the logs var userAgent = "compose/" + internal.Version // Client for integration with Docker Desktop features. type Client struct { apiEndpoint string client *http.Client } // NewClient creates a Desktop integration client for the provided in-memory // socket address (AF_UNIX or named pipe). func NewClient(apiEndpoint string) *Client { var transport http.RoundTripper = &http.Transport{ DisableCompression: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return memnet.DialEndpoint(ctx, apiEndpoint) }, } transport = otelhttp.NewTransport(transport) return &Client{ apiEndpoint: apiEndpoint, client: &http.Client{Transport: transport}, } } func (c *Client) Endpoint() string { return c.apiEndpoint } // Close releases any open connections. func (c *Client) Close() error { c.client.CloseIdleConnections() return nil } type PingResponse struct { ServerTime int64 `json:"serverTime"` } // Ping is a minimal API used to ensure that the server is available. func (c *Client) Ping(ctx context.Context) (*PingResponse, error) { req, err := c.newRequest(ctx, http.MethodGet, "/ping", http.NoBody) if err != nil { return nil, err } resp, err := c.client.Do(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) } var ret PingResponse if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil { return nil, err } return &ret, nil } type FeatureFlagResponse map[string]FeatureFlagValue type FeatureFlagValue struct { Enabled bool `json:"enabled"` } func (c *Client) FeatureFlags(ctx context.Context) (FeatureFlagResponse, error) { req, err := c.newRequest(ctx, http.MethodGet, "/features", http.NoBody) if err != nil { return nil, err } resp, err := c.client.Do(req) if err != nil { return nil, err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode) } var ret FeatureFlagResponse if err := json.NewDecoder(resp.Body).Decode(&ret); err != nil { return nil, err } return ret, nil } func (c *Client) newRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) { req, err := http.NewRequestWithContext(ctx, method, backendURL(path), body) if err != nil { return nil, err } req.Header.Set("User-Agent", userAgent) return req, nil } // backendURL generates a URL for the given API path. // // NOTE: Custom transport handles communication. The host is to create a valid // URL for the Go http.Client that is also descriptive in error/logs. func backendURL(path string) string { return "http://docker-desktop/" + strings.TrimPrefix(path, "/") }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/desktop/client_test.go
internal/desktop/client_test.go
/* Copyright 2024 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 desktop import ( "context" "os" "testing" "time" "github.com/stretchr/testify/require" ) func TestClientPing(t *testing.T) { if testing.Short() { t.Skip("Skipped in short mode - test connects to Docker Desktop") } desktopEndpoint := os.Getenv("COMPOSE_TEST_DESKTOP_ENDPOINT") if desktopEndpoint == "" { t.Skip("Skipping - COMPOSE_TEST_DESKTOP_ENDPOINT not defined") } ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) client := NewClient(desktopEndpoint) t.Cleanup(func() { _ = client.Close() }) now := time.Now() ret, err := client.Ping(ctx) require.NoError(t, err) serverTime := time.Unix(0, ret.ServerTime) require.True(t, now.Before(serverTime)) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/runtime_windows.go
internal/locker/runtime_windows.go
/* 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 locker import ( "os" "path/filepath" "golang.org/x/sys/windows" ) // Based on https://github.com/adrg/xdg // Licensed under MIT License (MIT) // Copyright (c) 2014 Adrian-George Bostan <adrg@epistack.com> func osDependentRunDir() (string, error) { flags := []uint32{windows.KF_FLAG_DEFAULT, windows.KF_FLAG_DEFAULT_PATH} for _, flag := range flags { p, _ := windows.KnownFolderPath(windows.FOLDERID_LocalAppData, flag|windows.KF_FLAG_DONT_VERIFY) if p != "" { return filepath.Join(p, "docker-compose"), nil } } appData, ok := os.LookupEnv("LOCALAPPDATA") if ok { return filepath.Join(appData, "docker-compose"), nil } home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, "AppData", "Local", "docker-compose"), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/runtime_unix.go
internal/locker/runtime_unix.go
//go:build linux || openbsd || freebsd /* 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 locker import ( "os" "path/filepath" "strconv" ) // Based on https://github.com/adrg/xdg // Licensed under MIT License (MIT) // Copyright (c) 2014 Adrian-George Bostan <adrg@epistack.com> func osDependentRunDir() (string, error) { run := filepath.Join("run", "user", strconv.Itoa(os.Getuid())) if _, err := os.Stat(run); err == nil { return run, nil } // /run/user/$uid is set by pam_systemd, but might not be present, especially in containerized environments home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, ".docker", "docker-compose"), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/pidfile_unix.go
internal/locker/pidfile_unix.go
//go:build !windows /* Copyright 2023 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 locker import ( "os" "github.com/docker/docker/pkg/pidfile" ) func (f *Pidfile) Lock() error { return pidfile.Write(f.path, os.Getpid()) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/pidfile_windows.go
internal/locker/pidfile_windows.go
//go:build windows /* Copyright 2023 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 locker import ( "os" "github.com/docker/docker/pkg/pidfile" "github.com/mitchellh/go-ps" ) func (f *Pidfile) Lock() error { newPID := os.Getpid() err := pidfile.Write(f.path, newPID) if err != nil { // Get PID registered in the file pid, errPid := pidfile.Read(f.path) if errPid != nil { return err } // Some users faced issues on Windows where the process written in the pidfile was identified as still existing // So we used a 2nd process library to verify if this not a false positive feedback // Check if the process exists process, errPid := ps.FindProcess(pid) if process == nil && errPid == nil { // If the process does not exist, remove the pidfile and try to lock again _ = os.Remove(f.path) return pidfile.Write(f.path, newPID) } } return err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/runtime_darwin.go
internal/locker/runtime_darwin.go
/* 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 locker import ( "os" "path/filepath" ) // Based on https://github.com/adrg/xdg // Licensed under MIT License (MIT) // Copyright (c) 2014 Adrian-George Bostan <adrg@epistack.com> func osDependentRunDir() (string, error) { home, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(home, "Library", "Application Support", "com.docker.compose"), nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/runtime.go
internal/locker/runtime.go
/* 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 locker import ( "os" ) func runDir() (string, error) { run, ok := os.LookupEnv("XDG_RUNTIME_DIR") if ok { return run, nil } path, err := osDependentRunDir() if err != nil { return "", err } err = os.MkdirAll(path, 0o700) return path, err }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/locker/pidfile.go
internal/locker/pidfile.go
/* Copyright 2023 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 locker import ( "fmt" "path/filepath" ) type Pidfile struct { path string } func NewPidfile(projectName string) (*Pidfile, error) { run, err := runDir() if err != nil { return nil, err } path := filepath.Join(run, fmt.Sprintf("%s.pid", projectName)) return &Pidfile{path: path}, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/paths/paths.go
internal/paths/paths.go
/* 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 paths import ( "os" "path/filepath" "strings" ) func IsChild(dir string, file string) bool { if dir == "" { return false } dir = filepath.Clean(dir) current := filepath.Clean(file) child := "." for { if strings.EqualFold(dir, current) { // If the two paths are exactly equal, then they must be the same. if dir == current { return true } // If the two paths are equal under case-folding, but not exactly equal, // then the only way to check if they're truly "equal" is to check // to see if we're on a case-insensitive file system. // // This is a notoriously tricky problem. See how dep solves it here: // https://github.com/golang/dep/blob/v0.5.4/internal/fs/fs.go#L33 // // because you can mount case-sensitive filesystems onto case-insensitive // file-systems, and vice versa :scream: // // We want to do as much of this check as possible with strings-only // (to avoid a file system read and error handling), so we only // do this check if we have no other choice. dirInfo, err := os.Stat(dir) if err != nil { return false } currentInfo, err := os.Stat(current) if err != nil { return false } if !os.SameFile(dirInfo, currentInfo) { return false } return true } if len(current) <= len(dir) || current == "." { return false } cDir := filepath.Dir(current) cBase := filepath.Base(current) child = filepath.Join(cBase, child) current = cDir } } // EncompassingPaths returns the minimal set of paths that root all paths // from the original collection. // // For example, ["/foo", "/foo/bar", "/foo", "/baz"] -> ["/foo", "/baz]. func EncompassingPaths(paths []string) []string { result := []string{} for _, current := range paths { isCovered := false hasRemovals := false for i, existing := range result { if IsChild(existing, current) { // The path is already covered, so there's no need to include it isCovered = true break } if IsChild(current, existing) { // Mark the element empty for removal. result[i] = "" hasRemovals = true } } if !isCovered { result = append(result, current) } if hasRemovals { // Remove all the empties newResult := []string{} for _, r := range result { if r != "" { newResult = append(newResult, r) } } result = newResult } } return result }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/oci/resolver.go
internal/oci/resolver.go
/* Copyright 2023 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 oci import ( "context" "io" "net/url" "slices" "strings" "github.com/containerd/containerd/v2/core/remotes" "github.com/containerd/containerd/v2/core/remotes/docker" "github.com/containerd/containerd/v2/pkg/labels" "github.com/containerd/errdefs" "github.com/distribution/reference" "github.com/docker/cli/cli/config/configfile" "github.com/moby/buildkit/util/contentutil" spec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/docker/compose/v5/internal/registry" ) // NewResolver setup an OCI Resolver based on docker/cli config to provide registry credentials func NewResolver(config *configfile.ConfigFile, insecureRegistries ...string) remotes.Resolver { return docker.NewResolver(docker.ResolverOptions{ Hosts: docker.ConfigureDefaultRegistries( docker.WithAuthorizer(docker.NewDockerAuthorizer( docker.WithAuthCreds(func(host string) (string, string, error) { host = registry.GetAuthConfigKey(host) auth, err := config.GetAuthConfig(host) if err != nil { return "", "", err } if auth.IdentityToken != "" { return "", auth.IdentityToken, nil } return auth.Username, auth.Password, nil }), )), docker.WithPlainHTTP(func(domain string) (bool, error) { // Should be used for testing **only** return slices.Contains(insecureRegistries, domain), nil }), ), }) } // Get retrieves a Named OCI resource and returns OCI Descriptor and Manifest func Get(ctx context.Context, resolver remotes.Resolver, ref reference.Named) (spec.Descriptor, []byte, error) { _, descriptor, err := resolver.Resolve(ctx, ref.String()) if err != nil { return spec.Descriptor{}, nil, err } fetcher, err := resolver.Fetcher(ctx, ref.String()) if err != nil { return spec.Descriptor{}, nil, err } fetch, err := fetcher.Fetch(ctx, descriptor) if err != nil { return spec.Descriptor{}, nil, err } content, err := io.ReadAll(fetch) if err != nil { return spec.Descriptor{}, nil, err } return descriptor, content, nil } func Copy(ctx context.Context, resolver remotes.Resolver, image reference.Named, named reference.Named) (spec.Descriptor, error) { src, desc, err := resolver.Resolve(ctx, image.String()) if err != nil { return spec.Descriptor{}, err } if desc.Annotations == nil { desc.Annotations = make(map[string]string) } // set LabelDistributionSource so push will actually use a registry mount refspec := reference.TrimNamed(image).String() u, err := url.Parse("dummy://" + refspec) if err != nil { return spec.Descriptor{}, err } source, repo := u.Hostname(), strings.TrimPrefix(u.Path, "/") desc.Annotations[labels.LabelDistributionSource+"."+source] = repo p, err := resolver.Pusher(ctx, named.Name()) if err != nil { return spec.Descriptor{}, err } f, err := resolver.Fetcher(ctx, src) if err != nil { return spec.Descriptor{}, err } err = contentutil.CopyChain(ctx, contentutil.FromPusher(p), contentutil.FromFetcher(f), desc) return desc, err } func Push(ctx context.Context, resolver remotes.Resolver, ref reference.Named, descriptor spec.Descriptor) error { pusher, err := resolver.Pusher(ctx, ref.String()) if err != nil { return err } ctx = remotes.WithMediaTypeKeyPrefix(ctx, ComposeYAMLMediaType, "artifact-") ctx = remotes.WithMediaTypeKeyPrefix(ctx, ComposeEnvFileMediaType, "artifact-") ctx = remotes.WithMediaTypeKeyPrefix(ctx, ComposeEmptyConfigMediaType, "config-") ctx = remotes.WithMediaTypeKeyPrefix(ctx, spec.MediaTypeEmptyJSON, "config-") push, err := pusher.Push(ctx, descriptor) if errdefs.IsAlreadyExists(err) { return nil } if err != nil { return err } _, err = push.Write(descriptor.Data) if err != nil { // Close the writer on error since Commit won't be called _ = push.Close() return err } // Commit will close the writer return push.Commit(ctx, int64(len(descriptor.Data)), descriptor.Digest) }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/oci/push.go
internal/oci/push.go
/* Copyright 2023 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 oci import ( "context" "encoding/json" "errors" "fmt" "net/http" "path/filepath" "slices" "time" "github.com/containerd/containerd/v2/core/remotes" pusherrors "github.com/containerd/containerd/v2/core/remotes/errors" "github.com/distribution/reference" "github.com/opencontainers/go-digest" "github.com/opencontainers/image-spec/specs-go" v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/docker/compose/v5/pkg/api" ) const ( // ComposeProjectArtifactType is the OCI 1.1-compliant artifact type value // for the generated image manifest. ComposeProjectArtifactType = "application/vnd.docker.compose.project" // ComposeYAMLMediaType is the media type for each layer (Compose file) // in the image manifest. ComposeYAMLMediaType = "application/vnd.docker.compose.file+yaml" // ComposeEmptyConfigMediaType is a media type used for the config descriptor // when doing OCI 1.0-style pushes. // // The content is always `{}`, the same as a normal empty descriptor, but // the specific media type allows clients to fall back to the config media // type to recognize the manifest as a Compose project since the artifact // type field is not available in OCI 1.0. // // This is based on guidance from the OCI 1.1 spec: // > Implementers note: artifacts have historically been created without // > an artifactType field, and tooling to work with artifacts should // > fallback to the config.mediaType value. ComposeEmptyConfigMediaType = "application/vnd.docker.compose.config.empty.v1+json" // ComposeEnvFileMediaType is the media type for each Env File layer in the image manifest. ComposeEnvFileMediaType = "application/vnd.docker.compose.envfile" ) // clientAuthStatusCodes are client (4xx) errors that are authentication // related. var clientAuthStatusCodes = []int{ http.StatusUnauthorized, http.StatusForbidden, http.StatusProxyAuthRequired, } func DescriptorForComposeFile(path string, content []byte) v1.Descriptor { return v1.Descriptor{ MediaType: ComposeYAMLMediaType, Digest: digest.FromString(string(content)), Size: int64(len(content)), Annotations: map[string]string{ "com.docker.compose.version": api.ComposeVersion, "com.docker.compose.file": filepath.Base(path), }, Data: content, } } func DescriptorForEnvFile(path string, content []byte) v1.Descriptor { return v1.Descriptor{ MediaType: ComposeEnvFileMediaType, Digest: digest.FromString(string(content)), Size: int64(len(content)), Annotations: map[string]string{ "com.docker.compose.version": api.ComposeVersion, "com.docker.compose.envfile": filepath.Base(path), }, Data: content, } } func PushManifest(ctx context.Context, resolver remotes.Resolver, named reference.Named, layers []v1.Descriptor, ociVersion api.OCIVersion) (v1.Descriptor, error) { // Check if we need an extra empty layer for the manifest config if ociVersion == api.OCIVersion1_1 || ociVersion == "" { err := push(ctx, resolver, named, v1.DescriptorEmptyJSON) if err != nil { return v1.Descriptor{}, err } } // prepare to push the manifest by pushing the layers layerDescriptors := make([]v1.Descriptor, len(layers)) for i := range layers { layerDescriptors[i] = layers[i] if err := push(ctx, resolver, named, layers[i]); err != nil { return v1.Descriptor{}, err } } if ociVersion != "" { // if a version was explicitly specified, use it return createAndPushManifest(ctx, resolver, named, layerDescriptors, ociVersion) } // try to push in the OCI 1.1 format but fallback to OCI 1.0 on 4xx errors // (other than auth) since it's most likely the result of the registry not // having support descriptor, err := createAndPushManifest(ctx, resolver, named, layerDescriptors, api.OCIVersion1_1) var pushErr pusherrors.ErrUnexpectedStatus if errors.As(err, &pushErr) && isNonAuthClientError(pushErr.StatusCode) { // TODO(milas): show a warning here (won't work with logrus) return createAndPushManifest(ctx, resolver, named, layerDescriptors, api.OCIVersion1_0) } return descriptor, err } func push(ctx context.Context, resolver remotes.Resolver, ref reference.Named, descriptor v1.Descriptor) error { fullRef, err := reference.WithDigest(reference.TagNameOnly(ref), descriptor.Digest) if err != nil { return err } return Push(ctx, resolver, fullRef, descriptor) } func createAndPushManifest(ctx context.Context, resolver remotes.Resolver, named reference.Named, layers []v1.Descriptor, ociVersion api.OCIVersion) (v1.Descriptor, error) { descriptor, toPush, err := generateManifest(layers, ociVersion) if err != nil { return v1.Descriptor{}, err } for _, p := range toPush { err = push(ctx, resolver, named, p) if err != nil { return v1.Descriptor{}, err } } return descriptor, nil } func isNonAuthClientError(statusCode int) bool { if statusCode < 400 || statusCode >= 500 { // not a client error return false } return !slices.Contains(clientAuthStatusCodes, statusCode) } func generateManifest(layers []v1.Descriptor, ociCompat api.OCIVersion) (v1.Descriptor, []v1.Descriptor, error) { var toPush []v1.Descriptor var config v1.Descriptor var artifactType string switch ociCompat { case api.OCIVersion1_0: // "Content other than OCI container images MAY be packaged using the image manifest. // When this is done, the config.mediaType value MUST be set to a value specific to // the artifact type or the empty value." // Source: https://github.com/opencontainers/image-spec/blob/main/manifest.md#guidelines-for-artifact-usage // // The `ComposeEmptyConfigMediaType` is used specifically for this purpose: // there is no config, and an empty descriptor is used for OCI 1.1 in // conjunction with the `ArtifactType`, but for OCI 1.0 compatibility, // tooling falls back to the config media type, so this is used to // indicate that it's not a container image but custom content. configData := []byte("{}") config = v1.Descriptor{ MediaType: ComposeEmptyConfigMediaType, Digest: digest.FromBytes(configData), Size: int64(len(configData)), Data: configData, } // N.B. OCI 1.0 does NOT support specifying the artifact type, so it's // left as an empty string to omit it from the marshaled JSON artifactType = "" toPush = append(toPush, config) case api.OCIVersion1_1: config = v1.DescriptorEmptyJSON artifactType = ComposeProjectArtifactType toPush = append(toPush, config) default: return v1.Descriptor{}, nil, fmt.Errorf("unsupported OCI version: %s", ociCompat) } manifest, err := json.Marshal(v1.Manifest{ Versioned: specs.Versioned{SchemaVersion: 2}, MediaType: v1.MediaTypeImageManifest, ArtifactType: artifactType, Config: config, Layers: layers, Annotations: map[string]string{ "org.opencontainers.image.created": time.Now().Format(time.RFC3339), }, }) if err != nil { return v1.Descriptor{}, nil, err } manifestDescriptor := v1.Descriptor{ MediaType: v1.MediaTypeImageManifest, Digest: digest.FromString(string(manifest)), Size: int64(len(manifest)), Annotations: map[string]string{ "com.docker.compose.version": api.ComposeVersion, }, ArtifactType: artifactType, Data: manifest, } toPush = append(toPush, manifestDescriptor) return manifestDescriptor, toPush, nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/experimental/experimental.go
internal/experimental/experimental.go
/* Copyright 2024 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 experimental import ( "context" "os" "strconv" "github.com/docker/compose/v5/internal/desktop" ) // envComposeExperimentalGlobal can be set to a falsy value (e.g. 0, false) to // globally opt-out of any experimental features in Compose. const envComposeExperimentalGlobal = "COMPOSE_EXPERIMENTAL" // State of experiments (enabled/disabled) based on environment and local config. type State struct { // active is false if experiments have been opted-out of globally. active bool desktopValues desktop.FeatureFlagResponse } func NewState() *State { // experimental features have individual controls, but users can opt out // of ALL experiments easily if desired experimentsActive := true if v := os.Getenv(envComposeExperimentalGlobal); v != "" { experimentsActive, _ = strconv.ParseBool(v) } return &State{ active: experimentsActive, } } func (s *State) Load(ctx context.Context, client *desktop.Client) error { if !s.active { // user opted out of experiments globally, no need to load state from // Desktop return nil } if client == nil { // not running under Docker Desktop return nil } desktopValues, err := client.FeatureFlags(ctx) if err != nil { return err } s.desktopValues = desktopValues return nil }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/registry/registry.go
internal/registry/registry.go
/* Copyright 2023 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 registry const ( // DefaultNamespace is the default namespace DefaultNamespace = "docker.io" // DefaultRegistryHost is the hostname for the default (Docker Hub) registry // used for pushing and pulling images. This hostname is hard-coded to handle // the conversion from image references without registry name (e.g. "ubuntu", // or "ubuntu:latest"), as well as references using the "docker.io" domain // name, which is used as canonical reference for images on Docker Hub, but // does not match the domain-name of Docker Hub's registry. DefaultRegistryHost = "registry-1.docker.io" // IndexHostname is the index hostname, used for authentication and image search. IndexHostname = "index.docker.io" // IndexServer is used for user auth and image search IndexServer = "https://" + IndexHostname + "/v1/" // IndexName is the name of the index IndexName = "docker.io" ) // GetAuthConfigKey special-cases using the full index address of the official // index as the AuthConfig key, and uses the (host)name[:port] for private indexes. func GetAuthConfigKey(indexName string) string { if indexName == IndexName || indexName == IndexHostname || indexName == DefaultRegistryHost { return IndexServer } return indexName }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false
docker/compose
https://github.com/docker/compose/blob/ec88588cd81a5b01eb2853d4ef538db4cb11e093/internal/sync/shared.go
internal/sync/shared.go
/* Copyright 2023 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 sync import ( "context" ) // PathMapping contains the Compose service and modified host system path. type PathMapping struct { // HostPath that was created/modified/deleted outside the container. // // This is the path as seen from the user's perspective, e.g. // - C:\Users\moby\Documents\hello-world\main.go (file on Windows) // - /Users/moby/Documents/hello-world (directory on macOS) HostPath string // ContainerPath for the target file inside the container (only populated // for sync events, not rebuild). // // This is the path as used in Docker CLI commands, e.g. // - /workdir/main.go // - /workdir/subdir ContainerPath string } type Syncer interface { Sync(ctx context.Context, service string, paths []*PathMapping) error }
go
Apache-2.0
ec88588cd81a5b01eb2853d4ef538db4cb11e093
2026-01-07T08:36:00.670150Z
false