Skip to content

Commit

Permalink
Add Navigation Menu to compose up
Browse files Browse the repository at this point in the history
Signed-off-by: Joana Hrotko <joana.hrotko@docker.com>
  • Loading branch information
jhrotko committed Mar 22, 2024
1 parent 3950460 commit fc8b195
Show file tree
Hide file tree
Showing 19 changed files with 587 additions and 47 deletions.
1 change: 1 addition & 0 deletions Dockerfile
Expand Up @@ -101,6 +101,7 @@ RUN --mount=type=bind,target=. \
FROM build-base AS test
ARG CGO_ENABLED=0
ARG BUILD_TAGS
ENV COMPOSE_MENU=FALSE
RUN --mount=type=bind,target=. \
--mount=type=cache,target=/root/.cache \
--mount=type=cache,target=/go/pkg/mod \
Expand Down
1 change: 1 addition & 0 deletions Makefile
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

PKG := github.com/docker/compose/v2
export COMPOSE_MENU = FALSE
VERSION ?= $(shell git describe --match 'v[0-9]*' --dirty='.m' --always --tags)

GO_LDFLAGS ?= -w -X ${PKG}/internal.Version=${VERSION}
Expand Down
14 changes: 14 additions & 0 deletions cmd/compose/compose.go
Expand Up @@ -65,6 +65,8 @@ const (
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"
)

type Backend interface {
Expand Down Expand Up @@ -620,3 +622,15 @@ var printerModes = []string{
ui.ModePlain,
ui.ModeQuiet,
}

func SetUnchangedOption(name string, experimentalFlag bool) bool {
var value bool
// If the var is defined we use that value first
if envVar, ok := os.LookupEnv(name); ok {
value = utils.StringToBool(envVar)
} else {
// if not, we try to get it from experimental feature flag
value = experimentalFlag
}
return value
}
57 changes: 33 additions & 24 deletions cmd/compose/up.go
Expand Up @@ -42,20 +42,22 @@ type composeOptions struct {

type upOptions struct {
*composeOptions
Detach bool
noStart bool
noDeps bool
cascadeStop bool
exitCodeFrom string
noColor bool
noPrefix bool
attachDependencies bool
attach []string
noAttach []string
timestamp bool
wait bool
waitTimeout int
watch bool
Detach bool
noStart bool
noDeps bool
cascadeStop 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) {
Expand Down Expand Up @@ -87,6 +89,7 @@ func upCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service, ex
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")
return validateFlags(&up, &create)
}),
RunE: p.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
Expand Down Expand Up @@ -128,6 +131,8 @@ func upCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service, ex
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 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 (Experimental). Incompatible with --detach.")
flags.MarkHidden("menu") //nolint:errcheck

return upCmd
}
Expand Down Expand Up @@ -161,7 +166,7 @@ func runUp(
ctx context.Context,
dockerCli command.Cli,
backend api.Service,
_ *experimental.State,
experimentals *experimental.State,
createOptions createOptions,
upOptions upOptions,
buildOptions buildOptions,
Expand All @@ -181,6 +186,9 @@ func runUp(
if err != nil {
return err
}
if !upOptions.navigationMenuChanged {
upOptions.navigationMenu = SetUnchangedOption(ComposeMenu, experimentals.NavBar())
}

var build *api.BuildOptions
if !createOptions.noBuild {
Expand Down Expand Up @@ -253,15 +261,16 @@ func runUp(
return backend.Up(ctx, project, api.UpOptions{
Create: create,
Start: api.StartOptions{
Project: project,
Attach: consumer,
AttachTo: attach,
ExitCodeFrom: upOptions.exitCodeFrom,
CascadeStop: upOptions.cascadeStop,
Wait: upOptions.wait,
WaitTimeout: timeout,
Watch: upOptions.watch,
Services: services,
Project: project,
Attach: consumer,
AttachTo: attach,
ExitCodeFrom: upOptions.exitCodeFrom,
CascadeStop: upOptions.cascadeStop,
Wait: upOptions.wait,
WaitTimeout: timeout,
Watch: upOptions.watch,
Services: services,
NavigationMenu: upOptions.navigationMenu,
},
})
}
Expand Down
67 changes: 67 additions & 0 deletions cmd/formatter/ansi.go
@@ -0,0 +1,67 @@
/*
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"
)

func ansi(code string) string {
return fmt.Sprintf("\033%s", code)
}
func SaveCursor() {
fmt.Print(ansi("7"))
}
func RestoreCursor() {
fmt.Print(ansi("8"))
}
func HideCursor() {
fmt.Print(ansi("[?25l"))
}
func ShowCursor() {
fmt.Print(ansi("[?25h"))
}
func MoveCursor(y, x int) {
fmt.Print(ansi(fmt.Sprintf("[%d;%dH", y, x)))
}
func MoveCursorX(pos int) {
fmt.Print(ansi(fmt.Sprintf("[%dG", pos)))
}
func ClearLine() {
// Does not move cursor from its current position
fmt.Print(ansi("[2K"))
}
func MoveCursorUp(lines int) {
// Does not add new lines
fmt.Print(ansi(fmt.Sprintf("[%dA", lines)))
}
func MoveCursorDown(lines int) {
// Does not add new lines
fmt.Print(ansi(fmt.Sprintf("[%dB", 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))
}
25 changes: 21 additions & 4 deletions cmd/formatter/colors.go
Expand Up @@ -35,6 +35,18 @@ var names = []string{
"white",
}

const (
BOLD = "1"
FAINT = "2"
ITALIC = "3"
UNDERLINE = "4"
)

const (
RESET = "0"
CYAN = "36"
)

const (
// Never use ANSI codes
Never = "never"
Expand Down Expand Up @@ -72,12 +84,17 @@ var monochrome = func(s string) string {
return s
}

func ansiColor(code, s string) string {
return fmt.Sprintf("%s%s%s", ansi(code), s, ansi("0"))
func ansiColor(code, s string, formatOpts ...string) string {
return fmt.Sprintf("%s%s%s", ansiColorCode(code, formatOpts...), s, ansiColorCode("0"))
}

func ansi(code string) string {
return fmt.Sprintf("\033[%sm", code)
// Everything about ansiColorCode color https://hyperskill.org/learn/step/18193
func ansiColorCode(code string, formatOpts ...string) string {
res := "\033["
for _, c := range formatOpts {
res = fmt.Sprintf("%s%s;", res, c)
}
return fmt.Sprintf("%s%sm", res, code)
}

func makeColorFunc(code string) colorFunc {
Expand Down
24 changes: 17 additions & 7 deletions cmd/formatter/logs.go
Expand Up @@ -102,19 +102,29 @@ func (l *logConsumer) Err(container, message string) {
l.write(l.stderr, container, message)
}

var navColor = makeColorFunc("90")

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.Split(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)
printFn := func() {
p := l.getPresenter(container)
timestamp := time.Now().Format(jsonmessage.RFC3339NanoFixed)
for _, line := range strings.Split(message, "\n") {
ClearLine()
if l.timestamp {
fmt.Fprintf(w, "%s%s%s\n", p.prefix, timestamp, line)
} else {
fmt.Fprintf(w, "%s%s\n", p.prefix, line)
}
}
}
if KeyboardManager != nil {
KeyboardManager.PrintKeyboardInfo(printFn)
} else {
printFn()
}
}

func (l *logConsumer) Status(container, msg string) {
Expand Down

0 comments on commit fc8b195

Please sign in to comment.