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
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/log/log.go
pkg/log/log.go
package log import ( "fmt" "io" "os" "path/filepath" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/sirupsen/logrus" ) // NewLogger returns a new logger func NewLogger(config *config.AppConfig, rollrusHook string) *logrus.Entry { var log *logrus.Logger if config.Debug || os.Getenv("DEBUG") == "TRUE" { log = newDevelopmentLogger(config) } else { log = newProductionLogger() } // highly recommended: tail -f development.log | humanlog // https://github.com/aybabtme/humanlog log.Formatter = &logrus.JSONFormatter{} return log.WithFields(logrus.Fields{ "debug": config.Debug, "version": config.Version, "commit": config.Commit, "buildDate": config.BuildDate, }) } func getLogLevel() logrus.Level { strLevel := os.Getenv("LOG_LEVEL") level, err := logrus.ParseLevel(strLevel) if err != nil { return logrus.DebugLevel } return level } func newDevelopmentLogger(config *config.AppConfig) *logrus.Logger { log := logrus.New() log.SetLevel(getLogLevel()) file, err := os.OpenFile(filepath.Join(config.ConfigDir, "development.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666) if err != nil { fmt.Println("unable to log to file") os.Exit(1) } log.SetOutput(file) return log } func newProductionLogger() *logrus.Logger { log := logrus.New() log.Out = io.Discard log.SetLevel(logrus.ErrorLevel) return log }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/cheatsheet/validate.go
pkg/cheatsheet/validate.go
package cheatsheet import ( "fmt" "io/fs" "log" "os" "path/filepath" "regexp" "github.com/jesseduffield/lazycore/pkg/utils" "github.com/pmezard/go-difflib/difflib" ) func Check() { dir := GetKeybindingsDir() tmpDir := filepath.Join(os.TempDir(), "lazydocker_cheatsheet") err := os.RemoveAll(tmpDir) if err != nil { log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err) } defer os.RemoveAll(tmpDir) if err = os.Mkdir(tmpDir, 0o700); err != nil { log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err) } generateAtDir(tmpDir) actualContent := obtainContent(dir) expectedContent := obtainContent(tmpDir) if expectedContent == "" { log.Fatal("empty expected content") } if actualContent != expectedContent { if err := difflib.WriteUnifiedDiff(os.Stdout, difflib.UnifiedDiff{ A: difflib.SplitLines(expectedContent), B: difflib.SplitLines(actualContent), FromFile: "Expected", FromDate: "", ToFile: "Actual", ToDate: "", Context: 1, }); err != nil { log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err) } fmt.Printf( "\nCheatsheets are out of date. Please run `%s` at the project root and commit the changes. "+ "If you run the script and no keybindings files are updated as a result, try rebasing onto master"+ "and trying again.\n", generateCheatsheetCmd, ) os.Exit(1) } fmt.Println("\nCheatsheets are up to date") } func GetKeybindingsDir() string { return utils.GetLazyRootDirectory() + "/docs/keybindings" } func obtainContent(dir string) string { re := regexp.MustCompile(`Keybindings_\w+\.md$`) content := "" err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if re.MatchString(path) { bytes, err := os.ReadFile(path) if err != nil { log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err) } content += fmt.Sprintf("\n%s\n\n", filepath.Base(path)) content += string(bytes) } return nil }) if err != nil { log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err) } return content }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/cheatsheet/generate.go
pkg/cheatsheet/generate.go
// This "script" generates a file called Keybindings_{{.LANG}}.md // in current working directory. // // The content of this generated file is a keybindings cheatsheet. // // To generate cheatsheet in english run: // LANG=en go run scripts/cheatsheet/main.go generate package cheatsheet import ( "fmt" "log" "os" "github.com/jesseduffield/lazydocker/pkg/app" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui" "github.com/jesseduffield/lazydocker/pkg/i18n" ) const ( generateCheatsheetCmd = "go run scripts/cheatsheet/main.go generate" ) type bindingSection struct { title string bindings []*gui.Binding } func Generate() { generateAtDir(GetKeybindingsDir()) } func generateAtDir(dir string) { mConfig, err := config.NewAppConfig("lazydocker", "", "", "", "", true, nil, "") if err != nil { panic(err) } for lang := range i18n.GetTranslationSets() { os.Setenv("LC_ALL", lang) mApp, _ := app.NewApp(mConfig) mApp.Gui.SetupFakeGui() file, err := os.Create(dir + "/Keybindings_" + lang + ".md") if err != nil { panic(err) } bindingSections := getBindingSections(mApp) content := formatSections(mApp, bindingSections) content = fmt.Sprintf( "_This file is auto-generated. To update, make the changes in the "+ "pkg/i18n directory and then run `%s` from the project root._\n\n%s", generateCheatsheetCmd, content, ) writeString(file, content) } } func writeString(file *os.File, str string) { _, err := file.WriteString(str) if err != nil { log.Fatal(err) } } func formatTitle(title string) string { return fmt.Sprintf("\n## %s\n\n", title) } func formatBinding(binding *gui.Binding) string { return fmt.Sprintf(" <kbd>%s</kbd>: %s\n", binding.GetKey(), binding.Description) } func getBindingSections(mApp *app.App) []*bindingSection { bindingSections := []*bindingSection{} for _, binding := range mApp.Gui.GetInitialKeybindings() { if binding.Description == "" { continue } viewName := binding.ViewName if viewName == "" { viewName = "global" } titleMap := map[string]string{ "global": mApp.Tr.GlobalTitle, "main": mApp.Tr.MainTitle, "project": mApp.Tr.ProjectTitle, "services": mApp.Tr.ServicesTitle, "containers": mApp.Tr.ContainersTitle, "images": mApp.Tr.ImagesTitle, "volumes": mApp.Tr.VolumesTitle, "networks": mApp.Tr.NetworksTitle, } bindingSections = addBinding(titleMap[viewName], bindingSections, binding) } return bindingSections } func addBinding(title string, bindingSections []*bindingSection, binding *gui.Binding) []*bindingSection { if binding.Description == "" { return bindingSections } for _, section := range bindingSections { if title == section.title { section.bindings = append(section.bindings, binding) return bindingSections } } section := &bindingSection{ title: title, bindings: []*gui.Binding{binding}, } return append(bindingSections, section) } func formatSections(mApp *app.App, bindingSections []*bindingSection) string { content := fmt.Sprintf("# Lazydocker %s\n", mApp.Tr.Menu) for _, section := range bindingSections { content += formatTitle(section.title) content += "<pre>\n" for _, binding := range section.bindings { content += formatBinding(binding) } content += "</pre>\n" } return content }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/container_logs.go
pkg/gui/container_logs.go
package gui import ( "context" "fmt" "io" "os" "os/signal" "time" "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/stdcopy" "github.com/fatih/color" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" ) func (gui *Gui) renderContainerLogsToMain(container *commands.Container) tasks.TaskFunc { return gui.NewTickerTask(TickerTaskOpts{ Func: func(ctx context.Context, notifyStopped chan struct{}) { gui.renderContainerLogsToMainAux(container, ctx, notifyStopped) }, Duration: time.Millisecond * 200, // TODO: see why this isn't working (when switching from Top tab to Logs tab in the services panel, the tops tab's content isn't removed) Before: func(ctx context.Context) { gui.clearMainView() }, Wrap: gui.Config.UserConfig.Gui.WrapMainPanel, Autoscroll: true, }) } func (gui *Gui) renderContainerLogsToMainAux(container *commands.Container, ctx context.Context, notifyStopped chan struct{}) { gui.clearMainView() defer func() { notifyStopped <- struct{}{} }() mainView := gui.Views.Main if err := gui.writeContainerLogs(container, ctx, mainView); err != nil { gui.Log.Error(err) } // if we are here because the task has been stopped, we should return // if we are here then the container must have exited, meaning we should wait until it's back again before ticker := time.NewTicker(time.Millisecond * 100) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: result, err := container.Inspect() if err != nil { // if we get an error, then the container has probably been removed so we'll get out of here gui.Log.Error(err) return } if result.State.Running { return } } } } func (gui *Gui) renderLogsToStdout(container *commands.Container) { stop := make(chan os.Signal, 1) defer signal.Stop(stop) ctx, cancel := context.WithCancel(context.Background()) go func() { signal.Notify(stop, os.Interrupt) <-stop cancel() }() if err := gui.g.Suspend(); err != nil { gui.Log.Error(err) return } defer func() { if err := gui.g.Resume(); err != nil { gui.Log.Error(err) } }() if err := gui.writeContainerLogs(container, ctx, os.Stdout); err != nil { gui.Log.Error(err) return } gui.promptToReturn() } func (gui *Gui) promptToReturn() { if !gui.Config.UserConfig.Gui.ReturnImmediately { fmt.Fprintf(os.Stdout, "\n\n%s", utils.ColoredString(gui.Tr.PressEnterToReturn, color.FgGreen)) // wait for enter press if _, err := fmt.Scanln(); err != nil { gui.Log.Error(err) } } } func (gui *Gui) writeContainerLogs(ctr *commands.Container, ctx context.Context, writer io.Writer) error { readCloser, err := gui.DockerCommand.Client.ContainerLogs(ctx, ctr.ID, container.LogsOptions{ ShowStdout: true, ShowStderr: true, Timestamps: gui.Config.UserConfig.Logs.Timestamps, Since: gui.Config.UserConfig.Logs.Since, Tail: gui.Config.UserConfig.Logs.Tail, Follow: true, }) if err != nil { gui.Log.Error(err) return err } defer readCloser.Close() if !ctr.DetailsLoaded() { // loop until the details load or context is cancelled, using timer ticker := time.NewTicker(time.Millisecond * 100) defer ticker.Stop() outer: for { select { case <-ctx.Done(): return nil case <-ticker.C: if ctr.DetailsLoaded() { break outer } } } } if ctr.Details.Config.Tty { _, err = io.Copy(writer, readCloser) if err != nil { return err } } else { _, err = stdcopy.StdCopy(writer, writer, readCloser) if err != nil { return err } } return nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/keybindings.go
pkg/gui/keybindings.go
package gui import ( "fmt" "github.com/jesseduffield/gocui" ) // Binding - a keybinding mapping a key and modifier to a handler. The keypress // is only handled if the given view has focus, or handled globally if the view // is "" type Binding struct { ViewName string Handler func(*gocui.Gui, *gocui.View) error Key interface{} // FIXME: find out how to get `gocui.Key | rune` Modifier gocui.Modifier Description string } // GetKey is a function. func (b *Binding) GetKey() string { key := 0 switch b.Key.(type) { case rune: key = int(b.Key.(rune)) case gocui.Key: key = int(b.Key.(gocui.Key)) } // special keys switch key { case 27: return "esc" case 13: return "enter" case 32: return "space" case 65514: return "►" case 65515: return "◄" case 65517: return "▲" case 65516: return "▼" case 65508: return "PgUp" case 65507: return "PgDn" } return fmt.Sprintf("%c", key) } // GetInitialKeybindings is a function. func (gui *Gui) GetInitialKeybindings() []*Binding { bindings := []*Binding{ { ViewName: "", Key: gocui.KeyEsc, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.escape), }, { ViewName: "", Key: 'q', Modifier: gocui.ModNone, Handler: gui.quit, }, { ViewName: "", Key: gocui.KeyCtrlC, Modifier: gocui.ModNone, Handler: gui.quit, }, { ViewName: "", Key: gocui.KeyPgup, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.scrollUpMain), }, { ViewName: "", Key: gocui.KeyPgdn, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.scrollDownMain), }, { ViewName: "", Key: gocui.KeyCtrlU, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.scrollUpMain), }, { ViewName: "", Key: gocui.KeyCtrlD, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.scrollDownMain), }, { ViewName: "", Key: gocui.KeyEnd, Modifier: gocui.ModNone, Handler: gui.autoScrollMain, }, { ViewName: "", Key: gocui.KeyHome, Modifier: gocui.ModNone, Handler: gui.jumpToTopMain, }, { ViewName: "", Key: 'x', Modifier: gocui.ModNone, Handler: gui.handleCreateOptionsMenu, }, { ViewName: "", Key: '?', Modifier: gocui.ModNone, Handler: gui.handleCreateOptionsMenu, }, { ViewName: "", Key: 'X', Modifier: gocui.ModNone, Handler: gui.handleCustomCommand, }, { ViewName: "project", Key: 'e', Modifier: gocui.ModNone, Handler: gui.handleEditConfig, Description: gui.Tr.EditConfig, }, { ViewName: "project", Key: 'o', Modifier: gocui.ModNone, Handler: gui.handleOpenConfig, Description: gui.Tr.OpenConfig, }, { ViewName: "project", Key: 'm', Modifier: gocui.ModNone, Handler: gui.handleViewAllLogs, Description: gui.Tr.ViewLogs, }, { ViewName: "menu", Key: gocui.KeyEsc, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.handleMenuClose), }, { ViewName: "menu", Key: 'q', Modifier: gocui.ModNone, Handler: wrappedHandler(gui.handleMenuClose), }, { ViewName: "menu", Key: ' ', Modifier: gocui.ModNone, Handler: wrappedHandler(gui.handleMenuPress), }, { ViewName: "menu", Key: gocui.KeyEnter, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.handleMenuPress), }, { ViewName: "menu", Key: 'y', Modifier: gocui.ModNone, Handler: wrappedHandler(gui.handleMenuPress), }, { ViewName: "information", Key: gocui.MouseLeft, Modifier: gocui.ModNone, Handler: gui.handleDonate, }, { ViewName: "containers", Key: 'd', Modifier: gocui.ModNone, Handler: gui.handleContainersRemoveMenu, Description: gui.Tr.Remove, }, { ViewName: "containers", Key: 'e', Modifier: gocui.ModNone, Handler: gui.handleHideStoppedContainers, Description: gui.Tr.HideStopped, }, { ViewName: "containers", Key: 'p', Modifier: gocui.ModNone, Handler: gui.handleContainerPause, Description: gui.Tr.Pause, }, { ViewName: "containers", Key: 's', Modifier: gocui.ModNone, Handler: gui.handleContainerStop, Description: gui.Tr.Stop, }, { ViewName: "containers", Key: 'r', Modifier: gocui.ModNone, Handler: gui.handleContainerRestart, Description: gui.Tr.Restart, }, { ViewName: "containers", Key: 'a', Modifier: gocui.ModNone, Handler: gui.handleContainerAttach, Description: gui.Tr.Attach, }, { ViewName: "containers", Key: 'm', Modifier: gocui.ModNone, Handler: gui.handleContainerViewLogs, Description: gui.Tr.ViewLogs, }, { ViewName: "containers", Key: 'E', Modifier: gocui.ModNone, Handler: gui.handleContainersExecShell, Description: gui.Tr.ExecShell, }, { ViewName: "containers", Key: 'c', Modifier: gocui.ModNone, Handler: gui.handleContainersCustomCommand, Description: gui.Tr.RunCustomCommand, }, { ViewName: "containers", Key: 'b', Modifier: gocui.ModNone, Handler: gui.handleContainersBulkCommand, Description: gui.Tr.ViewBulkCommands, }, { ViewName: "containers", Key: 'w', Modifier: gocui.ModNone, Handler: gui.handleContainersOpenInBrowserCommand, Description: gui.Tr.OpenInBrowser, }, { ViewName: "services", Key: 'u', Modifier: gocui.ModNone, Handler: gui.handleServiceUp, Description: gui.Tr.UpService, }, { ViewName: "services", Key: 'd', Modifier: gocui.ModNone, Handler: gui.handleServiceRemoveMenu, Description: gui.Tr.RemoveService, }, { ViewName: "services", Key: 's', Modifier: gocui.ModNone, Handler: gui.handleServiceStop, Description: gui.Tr.Stop, }, { ViewName: "services", Key: 'p', Modifier: gocui.ModNone, Handler: gui.handleServicePause, Description: gui.Tr.Pause, }, { ViewName: "services", Key: 'r', Modifier: gocui.ModNone, Handler: gui.handleServiceRestart, Description: gui.Tr.Restart, }, { ViewName: "services", Key: 'S', Modifier: gocui.ModNone, Handler: gui.handleServiceStart, Description: gui.Tr.Start, }, { ViewName: "services", Key: 'a', Modifier: gocui.ModNone, Handler: gui.handleServiceAttach, Description: gui.Tr.Attach, }, { ViewName: "services", Key: 'm', Modifier: gocui.ModNone, Handler: gui.handleServiceRenderLogsToMain, Description: gui.Tr.ViewLogs, }, { ViewName: "services", Key: 'U', Modifier: gocui.ModNone, Handler: gui.handleProjectUp, Description: gui.Tr.UpProject, }, { ViewName: "services", Key: 'D', Modifier: gocui.ModNone, Handler: gui.handleProjectDown, Description: gui.Tr.DownProject, }, { ViewName: "services", Key: 'R', Modifier: gocui.ModNone, Handler: gui.handleServiceRestartMenu, Description: gui.Tr.ViewRestartOptions, }, { ViewName: "services", Key: 'c', Modifier: gocui.ModNone, Handler: gui.handleServicesCustomCommand, Description: gui.Tr.RunCustomCommand, }, { ViewName: "services", Key: 'b', Modifier: gocui.ModNone, Handler: gui.handleServicesBulkCommand, Description: gui.Tr.ViewBulkCommands, }, { ViewName: "services", Key: 'E', Modifier: gocui.ModNone, Handler: gui.handleServicesExecShell, Description: gui.Tr.ExecShell, }, { ViewName: "services", Key: 'w', Modifier: gocui.ModNone, Handler: gui.handleServicesOpenInBrowserCommand, Description: gui.Tr.OpenInBrowser, }, { ViewName: "images", Key: 'c', Modifier: gocui.ModNone, Handler: gui.handleImagesCustomCommand, Description: gui.Tr.RunCustomCommand, }, { ViewName: "images", Key: 'd', Modifier: gocui.ModNone, Handler: gui.handleImagesRemoveMenu, Description: gui.Tr.RemoveImage, }, { ViewName: "images", Key: 'b', Modifier: gocui.ModNone, Handler: gui.handleImagesBulkCommand, Description: gui.Tr.ViewBulkCommands, }, { ViewName: "volumes", Key: 'c', Modifier: gocui.ModNone, Handler: gui.handleVolumesCustomCommand, Description: gui.Tr.RunCustomCommand, }, { ViewName: "volumes", Key: 'd', Modifier: gocui.ModNone, Handler: gui.handleVolumesRemoveMenu, Description: gui.Tr.RemoveVolume, }, { ViewName: "volumes", Key: 'b', Modifier: gocui.ModNone, Handler: gui.handleVolumesBulkCommand, Description: gui.Tr.ViewBulkCommands, }, { ViewName: "networks", Key: 'c', Modifier: gocui.ModNone, Handler: gui.handleNetworksCustomCommand, Description: gui.Tr.RunCustomCommand, }, { ViewName: "networks", Key: 'd', Modifier: gocui.ModNone, Handler: gui.handleNetworksRemoveMenu, Description: gui.Tr.RemoveNetwork, }, { ViewName: "networks", Key: 'b', Modifier: gocui.ModNone, Handler: gui.handleNetworksBulkCommand, Description: gui.Tr.ViewBulkCommands, }, { ViewName: "main", Key: gocui.KeyEsc, Modifier: gocui.ModNone, Handler: gui.handleExitMain, Description: gui.Tr.Return, }, { ViewName: "main", Key: gocui.KeyArrowLeft, Modifier: gocui.ModNone, Handler: gui.scrollLeftMain, }, { ViewName: "main", Key: gocui.KeyArrowRight, Modifier: gocui.ModNone, Handler: gui.scrollRightMain, }, { ViewName: "main", Key: 'h', Modifier: gocui.ModNone, Handler: gui.scrollLeftMain, }, { ViewName: "main", Key: 'l', Modifier: gocui.ModNone, Handler: gui.scrollRightMain, }, { ViewName: "filter", Key: gocui.KeyEnter, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.commitFilter), }, { ViewName: "filter", Key: gocui.KeyEsc, Modifier: gocui.ModNone, Handler: wrappedHandler(gui.escapeFilterPrompt), }, { ViewName: "", Key: 'J', Modifier: gocui.ModNone, Handler: wrappedHandler(gui.scrollDownMain), }, { ViewName: "", Key: 'K', Modifier: gocui.ModNone, Handler: wrappedHandler(gui.scrollUpMain), }, { ViewName: "", Key: 'H', Modifier: gocui.ModNone, Handler: gui.scrollLeftMain, }, { ViewName: "", Key: 'L', Modifier: gocui.ModNone, Handler: gui.scrollRightMain, }, { ViewName: "", Key: '+', Handler: wrappedHandler(gui.nextScreenMode), Description: gui.Tr.LcNextScreenMode, }, { ViewName: "", Key: '_', Handler: wrappedHandler(gui.prevScreenMode), Description: gui.Tr.LcPrevScreenMode, }, } for _, panel := range gui.allSidePanels() { bindings = append(bindings, []*Binding{ {ViewName: panel.GetView().Name(), Key: gocui.KeyArrowLeft, Modifier: gocui.ModNone, Handler: gui.previousView}, {ViewName: panel.GetView().Name(), Key: gocui.KeyArrowRight, Modifier: gocui.ModNone, Handler: gui.nextView}, {ViewName: panel.GetView().Name(), Key: 'h', Modifier: gocui.ModNone, Handler: gui.previousView}, {ViewName: panel.GetView().Name(), Key: 'l', Modifier: gocui.ModNone, Handler: gui.nextView}, {ViewName: panel.GetView().Name(), Key: gocui.KeyTab, Modifier: gocui.ModNone, Handler: gui.nextView}, {ViewName: panel.GetView().Name(), Key: gocui.KeyBacktab, Modifier: gocui.ModNone, Handler: gui.previousView}, }...) } setUpDownClickBindings := func(viewName string, onUp func() error, onDown func() error, onClick func() error) { bindings = append(bindings, []*Binding{ {ViewName: viewName, Key: 'k', Modifier: gocui.ModNone, Handler: wrappedHandler(onUp)}, {ViewName: viewName, Key: gocui.KeyArrowUp, Modifier: gocui.ModNone, Handler: wrappedHandler(onUp)}, {ViewName: viewName, Key: gocui.MouseWheelUp, Modifier: gocui.ModNone, Handler: wrappedHandler(onUp)}, {ViewName: viewName, Key: 'j', Modifier: gocui.ModNone, Handler: wrappedHandler(onDown)}, {ViewName: viewName, Key: gocui.KeyArrowDown, Modifier: gocui.ModNone, Handler: wrappedHandler(onDown)}, {ViewName: viewName, Key: gocui.MouseWheelDown, Modifier: gocui.ModNone, Handler: wrappedHandler(onDown)}, {ViewName: viewName, Key: gocui.MouseLeft, Modifier: gocui.ModNone, Handler: wrappedHandler(onClick)}, }...) } bindings = append(bindings, []*Binding{ {Handler: gui.handleGoTo(gui.Panels.Projects.View), Key: '1', Description: gui.Tr.FocusProjects}, {Handler: gui.handleGoTo(gui.Panels.Services.View), Key: '2', Description: gui.Tr.FocusServices}, {Handler: gui.handleGoTo(gui.Panels.Containers.View), Key: '3', Description: gui.Tr.FocusContainers}, {Handler: gui.handleGoTo(gui.Panels.Images.View), Key: '4', Description: gui.Tr.FocusImages}, {Handler: gui.handleGoTo(gui.Panels.Volumes.View), Key: '5', Description: gui.Tr.FocusVolumes}, {Handler: gui.handleGoTo(gui.Panels.Networks.View), Key: '6', Description: gui.Tr.FocusNetworks}, }...) for _, panel := range gui.allListPanels() { setUpDownClickBindings(panel.GetView().Name(), panel.HandlePrevLine, panel.HandleNextLine, panel.HandleClick) } setUpDownClickBindings("main", gui.scrollUpMain, gui.scrollDownMain, gui.handleMainClick) for _, panel := range gui.allSidePanels() { bindings = append(bindings, &Binding{ ViewName: panel.GetView().Name(), Key: gocui.KeyEnter, Modifier: gocui.ModNone, Handler: gui.handleEnterMain, Description: gui.Tr.FocusMain, }, &Binding{ ViewName: panel.GetView().Name(), Key: '[', Modifier: gocui.ModNone, Handler: wrappedHandler(panel.HandlePrevMainTab), Description: gui.Tr.PreviousContext, }, &Binding{ ViewName: panel.GetView().Name(), Key: ']', Modifier: gocui.ModNone, Handler: wrappedHandler(panel.HandleNextMainTab), Description: gui.Tr.NextContext, }, ) } for _, panel := range gui.allListPanels() { if !panel.IsFilterDisabled() { bindings = append(bindings, &Binding{ ViewName: panel.GetView().Name(), Key: '/', Modifier: gocui.ModNone, Handler: wrappedHandler(gui.handleOpenFilter), Description: gui.Tr.LcFilter, }) } } return bindings } func (gui *Gui) keybindings(g *gocui.Gui) error { bindings := gui.GetInitialKeybindings() for _, binding := range bindings { if err := g.SetKeybinding(binding.ViewName, binding.Key, binding.Modifier, binding.Handler); err != nil { return err } } if err := g.SetTabClickBinding("main", gui.onMainTabClick); err != nil { return err } return nil } func wrappedHandler(f func() error) func(*gocui.Gui, *gocui.View) error { return func(g *gocui.Gui, v *gocui.View) error { return f() } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/sort_container_test.go
pkg/gui/sort_container_test.go
package gui import ( "sort" "testing" "github.com/docker/docker/api/types/container" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/stretchr/testify/assert" ) func sampleContainers() []*commands.Container { return []*commands.Container{ { ID: "1", Name: "1", Container: container.Summary{ State: "exited", }, }, { ID: "2", Name: "2", Container: container.Summary{ State: "running", }, }, { ID: "3", Name: "3", Container: container.Summary{ State: "running", }, }, { ID: "4", Name: "4", Container: container.Summary{ State: "created", }, }, } } func expectedPerStatusContainers() []*commands.Container { return []*commands.Container{ { ID: "2", Name: "2", Container: container.Summary{ State: "running", }, }, { ID: "3", Name: "3", Container: container.Summary{ State: "running", }, }, { ID: "1", Name: "1", Container: container.Summary{ State: "exited", }, }, { ID: "4", Name: "4", Container: container.Summary{ State: "created", }, }, } } func expectedLegacySortedContainers() []*commands.Container { return []*commands.Container{ { ID: "1", Name: "1", Container: container.Summary{ State: "exited", }, }, { ID: "2", Name: "2", Container: container.Summary{ State: "running", }, }, { ID: "3", Name: "3", Container: container.Summary{ State: "running", }, }, { ID: "4", Name: "4", Container: container.Summary{ State: "created", }, }, } } func assertEqualContainers(t *testing.T, left *commands.Container, right *commands.Container) { t.Helper() assert.Equal(t, left.Container.State, right.Container.State) assert.Equal(t, left.Container.ID, right.Container.ID) assert.Equal(t, left.Name, right.Name) } func TestSortContainers(t *testing.T) { actual := sampleContainers() expected := expectedPerStatusContainers() sort.Slice(actual, func(i, j int) bool { return sortContainers(actual[i], actual[j], false) }) assert.Equal(t, len(actual), len(expected)) for i := 0; i < len(actual); i++ { assertEqualContainers(t, expected[i], actual[i]) } } func TestLegacySortedContainers(t *testing.T) { actual := sampleContainers() expected := expectedLegacySortedContainers() sort.Slice(actual, func(i, j int) bool { return sortContainers(actual[i], actual[j], true) }) assert.Equal(t, len(actual), len(expected)) for i := 0; i < len(actual); i++ { assertEqualContainers(t, expected[i], actual[i]) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/view_helpers.go
pkg/gui/view_helpers.go
package gui import ( "fmt" "sort" "strings" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" "github.com/spkg/bom" ) func (gui *Gui) handleGoTo(view *gocui.View) func(g *gocui.Gui, v *gocui.View) error { return func(g *gocui.Gui, v *gocui.View) error { gui.resetMainView() return gui.switchFocus(view) } } func (gui *Gui) nextView(g *gocui.Gui, v *gocui.View) error { sideViewNames := gui.sideViewNames() var focusedViewName string if v == nil || v.Name() == sideViewNames[len(sideViewNames)-1] { focusedViewName = sideViewNames[0] } else { viewName := v.Name() for i := range sideViewNames { if viewName == sideViewNames[i] { focusedViewName = sideViewNames[i+1] break } if i == len(sideViewNames)-1 { gui.Log.Info("not in list of views") return nil } } } focusedView, err := g.View(focusedViewName) if err != nil { panic(err) } gui.resetMainView() return gui.switchFocus(focusedView) } func (gui *Gui) previousView(g *gocui.Gui, v *gocui.View) error { sideViewNames := gui.sideViewNames() var focusedViewName string if v == nil || v.Name() == sideViewNames[0] { focusedViewName = sideViewNames[len(sideViewNames)-1] } else { viewName := v.Name() for i := range sideViewNames { if viewName == sideViewNames[i] { focusedViewName = sideViewNames[i-1] break } if i == len(sideViewNames)-1 { gui.Log.Info("not in list of views") return nil } } } focusedView, err := g.View(focusedViewName) if err != nil { panic(err) } gui.resetMainView() return gui.switchFocus(focusedView) } func (gui *Gui) resetMainView() { gui.State.Panels.Main.ObjectKey = "" gui.Views.Main.Wrap = gui.Config.UserConfig.Gui.WrapMainPanel } // if the cursor down past the last item, move it to the last line // nolint:unparam func (gui *Gui) focusPoint(selectedX int, selectedY int, lineCount int, v *gocui.View) { if selectedY < 0 || selectedY > lineCount { return } ox, oy := v.Origin() originalOy := oy cx, cy := v.Cursor() originalCy := cy _, height := v.Size() ly := utils.Max(height-1, 0) windowStart := oy windowEnd := oy + ly if selectedY < windowStart { oy = utils.Max(oy-(windowStart-selectedY), 0) } else if selectedY > windowEnd { oy += (selectedY - windowEnd) } if windowEnd > lineCount-1 { shiftAmount := (windowEnd - (lineCount - 1)) oy = utils.Max(oy-shiftAmount, 0) } if originalOy != oy { _ = v.SetOrigin(ox, oy) } cy = selectedY - oy if originalCy != cy { _ = v.SetCursor(cx, selectedY-oy) } } func (gui *Gui) FocusY(selectedY int, lineCount int, v *gocui.View) { gui.focusPoint(0, selectedY, lineCount, v) } func (gui *Gui) ResetOrigin(v *gocui.View) { _ = v.SetOrigin(0, 0) _ = v.SetCursor(0, 0) } func (gui *Gui) cleanString(s string) string { output := string(bom.Clean([]byte(s))) return utils.NormalizeLinefeeds(output) } func (gui *Gui) setViewContent(v *gocui.View, s string) error { v.Clear() fmt.Fprint(v, gui.cleanString(s)) return nil } // renderString resets the origin of a view and sets its content func (gui *Gui) renderString(g *gocui.Gui, viewName, s string) error { g.Update(func(*gocui.Gui) error { v, err := g.View(viewName) if err != nil { return nil // return gracefully if view has been deleted } if err := v.SetOrigin(0, 0); err != nil { return err } if err := v.SetCursor(0, 0); err != nil { return err } return gui.setViewContent(v, s) }) return nil } func (gui *Gui) RenderStringMain(s string) { _ = gui.renderString(gui.g, "main", s) } // reRenderString sets the main view's content, without changing its origin func (gui *Gui) reRenderStringMain(s string) { gui.reRenderString("main", s) } // reRenderString sets the view's content, without changing its origin func (gui *Gui) reRenderString(viewName, s string) { gui.g.Update(func(*gocui.Gui) error { v, err := gui.g.View(viewName) if err != nil { return nil // return gracefully if view has been deleted } return gui.setViewContent(v, s) }) } func (gui *Gui) optionsMapToString(optionsMap map[string]string) string { optionsArray := make([]string, 0) for key, description := range optionsMap { optionsArray = append(optionsArray, key+": "+description) } sort.Strings(optionsArray) return strings.Join(optionsArray, ", ") } func (gui *Gui) renderOptionsMap(optionsMap map[string]string) error { return gui.renderString(gui.g, "options", gui.optionsMapToString(optionsMap)) } func (gui *Gui) GetMainView() *gocui.View { return gui.Views.Main } func (gui *Gui) trimmedContent(v *gocui.View) string { return strings.TrimSpace(v.Buffer()) } func (gui *Gui) currentViewName() string { currentView := gui.g.CurrentView() // this can happen when the app is first starting up if currentView == nil { return gui.initiallyFocusedViewName() } return currentView.Name() } func (gui *Gui) resizeCurrentPopupPanel(g *gocui.Gui) error { v := g.CurrentView() if gui.isPopupPanel(v.Name()) { return gui.resizePopupPanel(v) } return nil } func (gui *Gui) resizePopupPanel(v *gocui.View) error { // If the confirmation panel is already displayed, just resize the width, // otherwise continue content := v.Buffer() x0, y0, x1, y1 := gui.getConfirmationPanelDimensions(v.Wrap, content) vx0, vy0, vx1, vy1 := v.Dimensions() if vx0 == x0 && vy0 == y0 && vx1 == x1 && vy1 == y1 { return nil } _, err := gui.g.SetView(v.Name(), x0, y0, x1, y1, 0) return err } func (gui *Gui) renderPanelOptions() error { currentView := gui.g.CurrentView() switch currentView.Name() { case "menu": return gui.renderMenuOptions() case "confirmation": return gui.renderConfirmationOptions() } return gui.renderGlobalOptions() } func (gui *Gui) isPopupPanel(viewName string) bool { return lo.Contains(gui.popupViewNames(), viewName) } func (gui *Gui) popupPanelFocused() bool { return gui.isPopupPanel(gui.currentViewName()) } func (gui *Gui) clearMainView() { mainView := gui.Views.Main mainView.Clear() _ = mainView.SetOrigin(0, 0) _ = mainView.SetCursor(0, 0) } func (gui *Gui) HandleClick(v *gocui.View, itemCount int, selectedLine *int, handleSelect func() error) error { wrappedHandleSelect := func(g *gocui.Gui, v *gocui.View) error { return handleSelect() } return gui.handleClickAux(v, itemCount, selectedLine, wrappedHandleSelect) } func (gui *Gui) handleClickAux(v *gocui.View, itemCount int, selectedLine *int, handleSelect func(*gocui.Gui, *gocui.View) error) error { if gui.popupPanelFocused() && v != nil && !gui.isPopupPanel(v.Name()) { return nil } _, cy := v.Cursor() _, oy := v.Origin() newSelectedLine := cy + oy if newSelectedLine < 0 { newSelectedLine = 0 } if newSelectedLine > itemCount-1 { newSelectedLine = itemCount - 1 } *selectedLine = newSelectedLine if gui.currentViewName() != v.Name() { if err := gui.switchFocus(v); err != nil { return err } } return handleSelect(gui.g, v) } func (gui *Gui) nextScreenMode() error { if gui.currentViewName() == "main" { gui.State.ScreenMode = prevIntInCycle([]WindowMaximisation{SCREEN_NORMAL, SCREEN_HALF, SCREEN_FULL}, gui.State.ScreenMode) return nil } gui.State.ScreenMode = nextIntInCycle([]WindowMaximisation{SCREEN_NORMAL, SCREEN_HALF, SCREEN_FULL}, gui.State.ScreenMode) return nil } func (gui *Gui) prevScreenMode() error { if gui.currentViewName() == "main" { gui.State.ScreenMode = nextIntInCycle([]WindowMaximisation{SCREEN_NORMAL, SCREEN_HALF, SCREEN_FULL}, gui.State.ScreenMode) return nil } gui.State.ScreenMode = prevIntInCycle([]WindowMaximisation{SCREEN_NORMAL, SCREEN_HALF, SCREEN_FULL}, gui.State.ScreenMode) return nil } func nextIntInCycle(sl []WindowMaximisation, current WindowMaximisation) WindowMaximisation { for i, val := range sl { if val == current { if i == len(sl)-1 { return sl[0] } return sl[i+1] } } return sl[0] } func prevIntInCycle(sl []WindowMaximisation, current WindowMaximisation) WindowMaximisation { for i, val := range sl { if val == current { if i > 0 { return sl[i-1] } return sl[len(sl)-1] } } return sl[len(sl)-1] } func (gui *Gui) CurrentView() *gocui.View { return gui.g.CurrentView() } func (gui *Gui) currentSidePanel() (panels.ISideListPanel, bool) { viewName := gui.currentViewName() for _, sidePanel := range gui.allSidePanels() { if sidePanel.GetView().Name() == viewName { return sidePanel, true } } return nil, false } // returns the current list panel. If no list panel is focused, returns false. func (gui *Gui) currentListPanel() (panels.ISideListPanel, bool) { viewName := gui.currentViewName() for _, sidePanel := range gui.allListPanels() { if sidePanel.GetView().Name() == viewName { return sidePanel, true } } return nil, false } func (gui *Gui) allSidePanels() []panels.ISideListPanel { return []panels.ISideListPanel{ gui.Panels.Projects, gui.Panels.Services, gui.Panels.Containers, gui.Panels.Images, gui.Panels.Volumes, gui.Panels.Networks, } } func (gui *Gui) allListPanels() []panels.ISideListPanel { return append(gui.allSidePanels(), gui.Panels.Menu) } func (gui *Gui) IsCurrentView(view *gocui.View) bool { return view == gui.CurrentView() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/arrangement.go
pkg/gui/arrangement.go
package gui import ( "github.com/jesseduffield/lazycore/pkg/boxlayout" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/mattn/go-runewidth" "github.com/samber/lo" ) // In this file we use the boxlayout package, along with knowledge about the app's state, // to arrange the windows (i.e. panels) on the screen. const INFO_SECTION_PADDING = " " func (gui *Gui) getWindowDimensions(informationStr string, appStatus string) map[string]boxlayout.Dimensions { minimumHeight := 9 minimumWidth := 10 width, height := gui.g.Size() if width < minimumWidth || height < minimumHeight { return boxlayout.ArrangeWindows(&boxlayout.Box{Window: "limit"}, 0, 0, width, height) } sideSectionWeight, mainSectionWeight := gui.getMidSectionWeights() sidePanelsDirection := boxlayout.COLUMN portraitMode := width <= 84 && height > 45 if portraitMode { sidePanelsDirection = boxlayout.ROW } showInfoSection := gui.Config.UserConfig.Gui.ShowBottomLine || gui.State.Filter.active infoSectionSize := 0 if showInfoSection { infoSectionSize = 1 } root := &boxlayout.Box{ Direction: boxlayout.ROW, Children: []*boxlayout.Box{ { Direction: sidePanelsDirection, Weight: 1, Children: []*boxlayout.Box{ { Direction: boxlayout.ROW, Weight: sideSectionWeight, ConditionalChildren: gui.sidePanelChildren, }, { Window: "main", Weight: mainSectionWeight, }, }, }, { Direction: boxlayout.COLUMN, Size: infoSectionSize, Children: gui.infoSectionChildren(informationStr, appStatus), }, }, } return boxlayout.ArrangeWindows(root, 0, 0, width, height) } func (gui *Gui) getMidSectionWeights() (int, int) { currentWindow := gui.currentStaticWindowName() // we originally specified this as a ratio i.e. .20 would correspond to a weight of 1 against 4 sidePanelWidthRatio := gui.Config.UserConfig.Gui.SidePanelWidth // we could make this better by creating ratios like 2:3 rather than always 1:something mainSectionWeight := int(1/sidePanelWidthRatio) - 1 sideSectionWeight := 1 if currentWindow == "main" && gui.State.ScreenMode == SCREEN_FULL { mainSectionWeight = 1 sideSectionWeight = 0 } else { if gui.State.ScreenMode == SCREEN_HALF { mainSectionWeight = 1 } else if gui.State.ScreenMode == SCREEN_FULL { mainSectionWeight = 0 } } return sideSectionWeight, mainSectionWeight } func (gui *Gui) infoSectionChildren(informationStr string, appStatus string) []*boxlayout.Box { result := []*boxlayout.Box{} if len(appStatus) > 0 { result = append(result, &boxlayout.Box{ Window: "appStatus", Size: runewidth.StringWidth(appStatus) + runewidth.StringWidth(INFO_SECTION_PADDING), }, ) } if gui.State.Filter.active { return append(result, []*boxlayout.Box{ { Window: "filterPrefix", Size: runewidth.StringWidth(gui.filterPrompt()), }, { Window: "filter", Weight: 1, }, }...) } result = append(result, []*boxlayout.Box{ { Window: "options", Weight: 1, }, { Window: "information", // unlike appStatus, informationStr has various colors so we need to decolorise before taking the length Size: runewidth.StringWidth(INFO_SECTION_PADDING) + runewidth.StringWidth(utils.Decolorise(informationStr)), }, }..., ) return result } func (gui *Gui) sideViewNames() []string { visibleSidePanels := lo.Filter(gui.allSidePanels(), func(panel panels.ISideListPanel, _ int) bool { return !panel.IsHidden() }) return lo.Map(visibleSidePanels, func(panel panels.ISideListPanel, _ int) string { return panel.GetView().Name() }) } func (gui *Gui) sidePanelChildren(width int, height int) []*boxlayout.Box { currentWindow := gui.currentSideWindowName() sideWindowNames := gui.sideViewNames() if gui.State.ScreenMode == SCREEN_FULL || gui.State.ScreenMode == SCREEN_HALF { fullHeightBox := func(window string) *boxlayout.Box { if window == currentWindow { return &boxlayout.Box{ Window: window, Weight: 1, } } else { return &boxlayout.Box{ Window: window, Size: 0, } } } return lo.Map(sideWindowNames, func(window string, _ int) *boxlayout.Box { return fullHeightBox(window) }) } else if height >= 28 { accordionMode := gui.Config.UserConfig.Gui.ExpandFocusedSidePanel accordionBox := func(defaultBox *boxlayout.Box) *boxlayout.Box { if accordionMode && defaultBox.Window == currentWindow { return &boxlayout.Box{ Window: defaultBox.Window, Weight: 2, } } return defaultBox } return append([]*boxlayout.Box{ { Window: sideWindowNames[0], Size: 3, }, }, lo.Map(sideWindowNames[1:], func(window string, _ int) *boxlayout.Box { return accordionBox(&boxlayout.Box{Window: window, Weight: 1}) })...) } else { squashedHeight := 1 if height >= 21 { squashedHeight = 3 } squashedSidePanelBox := func(window string) *boxlayout.Box { if window == currentWindow { return &boxlayout.Box{ Window: window, Weight: 1, } } else { return &boxlayout.Box{ Window: window, Size: squashedHeight, } } } return lo.Map(sideWindowNames, func(window string, _ int) *boxlayout.Box { return squashedSidePanelBox(window) }) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/networks_panel.go
pkg/gui/networks_panel.go
package gui import ( "strconv" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) getNetworksPanel() *panels.SideListPanel[*commands.Network] { return &panels.SideListPanel[*commands.Network]{ ContextState: &panels.ContextState[*commands.Network]{ GetMainTabs: func() []panels.MainTab[*commands.Network] { return []panels.MainTab[*commands.Network]{ { Key: "config", Title: gui.Tr.ConfigTitle, Render: gui.renderNetworkConfig, }, } }, GetItemContextCacheKey: func(network *commands.Network) string { return "networks-" + network.Name }, }, ListPanel: panels.ListPanel[*commands.Network]{ List: panels.NewFilteredList[*commands.Network](), View: gui.Views.Networks, }, NoItemsMessage: gui.Tr.NoNetworks, Gui: gui.intoInterface(), // we're sorting these networks based on whether they have labels defined, // because those are the ones you typically care about. // Within that, we also sort them alphabetically Sort: func(a *commands.Network, b *commands.Network) bool { return a.Name < b.Name }, GetTableCells: presentation.GetNetworkDisplayStrings, } } func (gui *Gui) renderNetworkConfig(network *commands.Network) tasks.TaskFunc { return gui.NewSimpleRenderStringTask(func() string { return gui.networkConfigStr(network) }) } func (gui *Gui) networkConfigStr(network *commands.Network) string { padding := 15 output := "" output += utils.WithPadding("ID: ", padding) + network.Network.ID + "\n" output += utils.WithPadding("Name: ", padding) + network.Name + "\n" output += utils.WithPadding("Driver: ", padding) + network.Network.Driver + "\n" output += utils.WithPadding("Scope: ", padding) + network.Network.Scope + "\n" output += utils.WithPadding("EnabledIPV6: ", padding) + strconv.FormatBool(network.Network.EnableIPv6) + "\n" output += utils.WithPadding("Internal: ", padding) + strconv.FormatBool(network.Network.Internal) + "\n" output += utils.WithPadding("Attachable: ", padding) + strconv.FormatBool(network.Network.Attachable) + "\n" output += utils.WithPadding("Ingress: ", padding) + strconv.FormatBool(network.Network.Ingress) + "\n" output += utils.WithPadding("Containers: ", padding) if len(network.Network.Containers) > 0 { output += "\n" for _, v := range network.Network.Containers { output += utils.FormatMapItem(padding, v.Name, v.EndpointID) } } else { output += "none\n" } output += "\n" output += utils.WithPadding("Labels: ", padding) + utils.FormatMap(padding, network.Network.Labels) + "\n" output += utils.WithPadding("Options: ", padding) + utils.FormatMap(padding, network.Network.Options) return output } func (gui *Gui) reloadNetworks() error { if err := gui.refreshStateNetworks(); err != nil { return err } return gui.Panels.Networks.RerenderList() } func (gui *Gui) refreshStateNetworks() error { networks, err := gui.DockerCommand.RefreshNetworks() if err != nil { return err } gui.Panels.Networks.SetItems(networks) return nil } func (gui *Gui) handleNetworksRemoveMenu(g *gocui.Gui, v *gocui.View) error { network, err := gui.Panels.Networks.GetSelectedItem() if err != nil { return nil } type removeNetworkOption struct { description string command string } options := []*removeNetworkOption{ { description: gui.Tr.Remove, command: utils.WithShortSha("docker network rm " + network.Name), }, } menuItems := lo.Map(options, func(option *removeNetworkOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{option.description, color.New(color.FgRed).Sprint(option.command)}, OnPress: func() error { return gui.WithWaitingStatus(gui.Tr.RemovingStatus, func() error { if err := network.Remove(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, } }) return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) handlePruneNetworks() error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmPruneNetworks, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.PruningStatus, func() error { err := gui.DockerCommand.PruneNetworks() if err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, nil) } func (gui *Gui) handleNetworksCustomCommand(g *gocui.Gui, v *gocui.View) error { network, err := gui.Panels.Networks.GetSelectedItem() if err != nil { return nil } commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{ Network: network, }) customCommands := gui.Config.UserConfig.CustomCommands.Networks return gui.createCustomCommandMenu(customCommands, commandObject) } func (gui *Gui) handleNetworksBulkCommand(g *gocui.Gui, v *gocui.View) error { baseBulkCommands := []config.CustomCommand{ { Name: gui.Tr.PruneNetworks, InternalFunction: gui.handlePruneNetworks, }, } bulkCommands := append(baseBulkCommands, gui.Config.UserConfig.BulkCommands.Networks...) commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{}) return gui.createBulkCommandMenu(bulkCommands, commandObject) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/window.go
pkg/gui/window.go
package gui // func (gui *Gui) currentWindow() string { // // at the moment, we only have one view per window in lazydocker, so we // // are using the view name as the window name // return gui.currentViewName() // } // excludes popups func (gui *Gui) currentStaticWindowName() string { return gui.currentStaticViewName() } func (gui *Gui) currentSideWindowName() string { return gui.currentSideViewName() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/app_status_manager.go
pkg/gui/app_status_manager.go
package gui import ( "time" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/utils" ) type appStatus struct { name string statusType string duration int } type statusManager struct { statuses []appStatus } func (m *statusManager) removeStatus(name string) { newStatuses := []appStatus{} for _, status := range m.statuses { if status.name != name { newStatuses = append(newStatuses, status) } } m.statuses = newStatuses } func (m *statusManager) addWaitingStatus(name string) { m.removeStatus(name) newStatus := appStatus{ name: name, statusType: "waiting", duration: 0, } m.statuses = append([]appStatus{newStatus}, m.statuses...) } func (m *statusManager) getStatusString() string { if len(m.statuses) == 0 { return "" } topStatus := m.statuses[0] if topStatus.statusType == "waiting" { return topStatus.name + " " + utils.Loader() } return topStatus.name } // WithWaitingStatus wraps a function and shows a waiting status while the function is still executing func (gui *Gui) WithWaitingStatus(name string, f func() error) error { go func() { gui.statusManager.addWaitingStatus(name) defer func() { gui.statusManager.removeStatus(name) }() go func() { ticker := time.NewTicker(time.Millisecond * 50) defer ticker.Stop() for range ticker.C { appStatus := gui.statusManager.getStatusString() if appStatus == "" { return } if err := gui.renderString(gui.g, "appStatus", appStatus); err != nil { gui.Log.Warn(err) } } }() if err := f(); err != nil { gui.g.Update(func(g *gocui.Gui) error { return gui.createErrorPanel(err.Error()) }) } }() return nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/tasks_adapter.go
pkg/gui/tasks_adapter.go
package gui import ( "context" "time" "github.com/jesseduffield/lazydocker/pkg/tasks" ) func (gui *Gui) QueueTask(f func(ctx context.Context)) error { return gui.taskManager.NewTask(f) } type RenderStringTaskOpts struct { Autoscroll bool Wrap bool GetStrContent func() string } type TaskOpts struct { Autoscroll bool Wrap bool Func func(ctx context.Context) } type TickerTaskOpts struct { Duration time.Duration Before func(ctx context.Context) Func func(ctx context.Context, notifyStopped chan struct{}) Autoscroll bool Wrap bool } func (gui *Gui) NewRenderStringTask(opts RenderStringTaskOpts) tasks.TaskFunc { taskOpts := TaskOpts{ Autoscroll: opts.Autoscroll, Wrap: opts.Wrap, Func: func(ctx context.Context) { gui.RenderStringMain(opts.GetStrContent()) }, } return gui.NewTask(taskOpts) } // assumes it's cheap to obtain the content (otherwise we would pass a function that returns the content) func (gui *Gui) NewSimpleRenderStringTask(getContent func() string) tasks.TaskFunc { return gui.NewRenderStringTask(RenderStringTaskOpts{ GetStrContent: getContent, Autoscroll: false, Wrap: gui.Config.UserConfig.Gui.WrapMainPanel, }) } func (gui *Gui) NewTask(opts TaskOpts) tasks.TaskFunc { return func(ctx context.Context) { mainView := gui.Views.Main mainView.Autoscroll = opts.Autoscroll mainView.Wrap = opts.Wrap opts.Func(ctx) } } // NewTickerTask is a convenience function for making a new task that repeats some action once per e.g. second // the before function gets called after the lock is obtained, but before the ticker starts. // if you handle a message on the stop channel in f() you need to send a message on the notifyStopped channel because returning is not sufficient. Here, unlike in a regular task, simply returning means we're now going to wait till the next tick to run again. func (gui *Gui) NewTickerTask(opts TickerTaskOpts) tasks.TaskFunc { notifyStopped := make(chan struct{}, 10) task := func(ctx context.Context) { if opts.Before != nil { opts.Before(ctx) } tickChan := time.NewTicker(opts.Duration) defer tickChan.Stop() // calling f first so that we're not waiting for the first tick opts.Func(ctx, notifyStopped) for { select { case <-notifyStopped: gui.Log.Info("exiting ticker task due to notifyStopped channel") return case <-ctx.Done(): gui.Log.Info("exiting ticker task due to stopped channel") return case <-tickChan.C: gui.Log.Info("running ticker task again") opts.Func(ctx, notifyStopped) } } } taskOpts := TaskOpts{ Autoscroll: opts.Autoscroll, Wrap: opts.Wrap, Func: task, } return gui.NewTask(taskOpts) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/custom_commands.go
pkg/gui/custom_commands.go
package gui import ( "github.com/fatih/color" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) createCommandMenu(customCommands []config.CustomCommand, commandObject commands.CommandObject, title string, waitingStatus string) error { menuItems := lo.Map(customCommands, func(command config.CustomCommand, _ int) *types.MenuItem { resolvedCommand := utils.ApplyTemplate(command.Command, commandObject) onPress := func() error { if command.InternalFunction != nil { return command.InternalFunction() } if command.Shell { resolvedCommand = gui.OSCommand.NewCommandStringWithShell(resolvedCommand) } // if we have a command for attaching, we attach and return the subprocess error if command.Attach { return gui.runSubprocess(gui.OSCommand.ExecutableFromString(resolvedCommand)) } return gui.WithWaitingStatus(waitingStatus, func() error { if err := gui.OSCommand.RunCommand(resolvedCommand); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) } return &types.MenuItem{ LabelColumns: []string{ command.Name, utils.ColoredString(utils.WithShortSha(resolvedCommand), color.FgCyan), }, OnPress: onPress, } }) return gui.Menu(CreateMenuOptions{ Title: title, Items: menuItems, }) } func (gui *Gui) createCustomCommandMenu(customCommands []config.CustomCommand, commandObject commands.CommandObject) error { return gui.createCommandMenu(customCommands, commandObject, gui.Tr.CustomCommandTitle, gui.Tr.RunningCustomCommandStatus) } func (gui *Gui) createBulkCommandMenu(customCommands []config.CustomCommand, commandObject commands.CommandObject) error { return gui.createCommandMenu(customCommands, commandObject, gui.Tr.BulkCommandTitle, gui.Tr.RunningBulkCommandStatus) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/views.go
pkg/gui/views.go
package gui import ( "os" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/samber/lo" ) // See https://github.com/xtermjs/xterm.js/issues/4238 // VSCode is soon to fix this in an upcoming update. // Once that's done, we can scrap the HIDE_UNDERSCORES variable var ( underscoreEnvChecked bool hideUnderscores bool ) func hideUnderScores() bool { if !underscoreEnvChecked { hideUnderscores = os.Getenv("TERM_PROGRAM") == "vscode" underscoreEnvChecked = true } return hideUnderscores } type Views struct { // side panels Project *gocui.View Services *gocui.View Containers *gocui.View Images *gocui.View Volumes *gocui.View Networks *gocui.View // main panel Main *gocui.View // bottom line Options *gocui.View Information *gocui.View AppStatus *gocui.View // text that prompts you to enter text in the Filter view FilterPrefix *gocui.View // appears next to the SearchPrefix view, it's where you type in the search string Filter *gocui.View // popups Confirmation *gocui.View Menu *gocui.View // will cover everything when it appears Limit *gocui.View } type viewNameMapping struct { viewPtr **gocui.View name string // if true, we handle the position/size of the view in arrangement.go. Otherwise // we handle it manually. autoPosition bool } func (gui *Gui) orderedViewNameMappings() []viewNameMapping { return []viewNameMapping{ // first layer. Ordering within this layer does not matter because there are // no overlapping views {viewPtr: &gui.Views.Project, name: "project", autoPosition: true}, {viewPtr: &gui.Views.Services, name: "services", autoPosition: true}, {viewPtr: &gui.Views.Containers, name: "containers", autoPosition: true}, {viewPtr: &gui.Views.Images, name: "images", autoPosition: true}, {viewPtr: &gui.Views.Volumes, name: "volumes", autoPosition: true}, {viewPtr: &gui.Views.Networks, name: "networks", autoPosition: true}, {viewPtr: &gui.Views.Main, name: "main", autoPosition: true}, // bottom line {viewPtr: &gui.Views.Options, name: "options", autoPosition: true}, {viewPtr: &gui.Views.AppStatus, name: "appStatus", autoPosition: true}, {viewPtr: &gui.Views.Information, name: "information", autoPosition: true}, {viewPtr: &gui.Views.Filter, name: "filter", autoPosition: true}, {viewPtr: &gui.Views.FilterPrefix, name: "filterPrefix", autoPosition: true}, // popups. {viewPtr: &gui.Views.Menu, name: "menu", autoPosition: false}, {viewPtr: &gui.Views.Confirmation, name: "confirmation", autoPosition: false}, // this guy will cover everything else when it appears {viewPtr: &gui.Views.Limit, name: "limit", autoPosition: true}, } } func (gui *Gui) createAllViews() error { frameRunes := []rune{'─', '│', '╭', '╮', '╰', '╯'} switch gui.Config.UserConfig.Gui.Border { case "single": frameRunes = []rune{'─', '│', '┌', '┐', '└', '┘'} case "double": frameRunes = []rune{'═', '║', '╔', '╗', '╚', '╝'} case "hidden": frameRunes = []rune{' ', ' ', ' ', ' ', ' ', ' '} } var err error for _, mapping := range gui.orderedViewNameMappings() { *mapping.viewPtr, err = gui.prepareView(mapping.name) if err != nil && err.Error() != UNKNOWN_VIEW_ERROR_MSG { return err } (*mapping.viewPtr).FrameRunes = frameRunes (*mapping.viewPtr).FgColor = gocui.ColorDefault } selectedLineBgColor := GetGocuiStyle(gui.Config.UserConfig.Gui.Theme.SelectedLineBgColor) gui.Views.Main.Wrap = gui.Config.UserConfig.Gui.WrapMainPanel // when you run a docker container with the -it flags (interactive mode) it adds carriage returns for some reason. This is not docker's fault, it's an os-level default. gui.Views.Main.IgnoreCarriageReturns = true gui.Views.Project.Title = gui.Tr.ProjectTitle gui.Views.Project.TitlePrefix = "[1]" gui.Views.Services.Highlight = true gui.Views.Services.Title = gui.Tr.ServicesTitle gui.Views.Services.TitlePrefix = "[2]" gui.Views.Services.SelBgColor = selectedLineBgColor gui.Views.Containers.Highlight = true gui.Views.Containers.SelBgColor = selectedLineBgColor if gui.Config.UserConfig.Gui.ShowAllContainers || !gui.DockerCommand.InDockerComposeProject { gui.Views.Containers.Title = gui.Tr.ContainersTitle } else { gui.Views.Containers.Title = gui.Tr.StandaloneContainersTitle } gui.Views.Containers.TitlePrefix = "[3]" gui.Views.Images.Highlight = true gui.Views.Images.Title = gui.Tr.ImagesTitle gui.Views.Images.SelBgColor = selectedLineBgColor gui.Views.Images.TitlePrefix = "[4]" gui.Views.Volumes.Highlight = true gui.Views.Volumes.Title = gui.Tr.VolumesTitle gui.Views.Volumes.TitlePrefix = "[5]" gui.Views.Volumes.SelBgColor = selectedLineBgColor gui.Views.Networks.Highlight = true gui.Views.Networks.Title = gui.Tr.NetworksTitle gui.Views.Networks.TitlePrefix = "[6]" gui.Views.Networks.SelBgColor = selectedLineBgColor gui.Views.Options.Frame = false gui.Views.Options.FgColor = gui.GetOptionsPanelTextColor() gui.Views.AppStatus.FgColor = gocui.ColorCyan gui.Views.AppStatus.Frame = false gui.Views.Information.Frame = false gui.Views.Information.FgColor = gocui.ColorGreen gui.Views.Confirmation.Visible = false gui.Views.Confirmation.Wrap = true gui.Views.Menu.Visible = false gui.Views.Menu.SelBgColor = selectedLineBgColor gui.Views.Limit.Visible = false gui.Views.Limit.Title = gui.Tr.NotEnoughSpace gui.Views.Limit.Wrap = true gui.Views.FilterPrefix.BgColor = gocui.ColorDefault gui.Views.FilterPrefix.FgColor = gocui.ColorGreen gui.Views.FilterPrefix.Frame = false gui.Views.Filter.BgColor = gocui.ColorDefault gui.Views.Filter.FgColor = gocui.ColorGreen gui.Views.Filter.Editable = true gui.Views.Filter.Frame = false gui.Views.Filter.Editor = gocui.EditorFunc(gui.wrapEditor(gocui.SimpleEditor)) return nil } func (gui *Gui) setInitialViewContent() error { if err := gui.renderString(gui.g, "information", gui.getInformationContent()); err != nil { return err } _ = gui.setViewContent(gui.Views.FilterPrefix, gui.filterPrompt()) return nil } func (gui *Gui) getInformationContent() string { informationStr := gui.Config.Version if !gui.g.Mouse { return informationStr } attrs := []color.Attribute{color.FgMagenta} if !hideUnderScores() { attrs = append(attrs, color.Underline) } donate := color.New(attrs...).Sprint(gui.Tr.Donate) return donate + " " + informationStr } func (gui *Gui) popupViewNames() []string { return []string{"confirmation", "menu"} } // these views have their position and size determined by arrangement.go func (gui *Gui) autoPositionedViewNames() []string { views := lo.Filter(gui.orderedViewNameMappings(), func(viewNameMapping viewNameMapping, _ int) bool { return viewNameMapping.autoPosition }) return lo.Map(views, func(viewNameMapping viewNameMapping, _ int) string { return viewNameMapping.name }) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/containers_panel.go
pkg/gui/containers_panel.go
package gui import ( "context" "fmt" "strings" "time" "github.com/docker/docker/api/types/container" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) getContainersPanel() *panels.SideListPanel[*commands.Container] { // Standalone containers are containers which are either one-off containers, or whose service is not part of this docker-compose context. isStandaloneContainer := func(container *commands.Container) bool { if container.OneOff || container.ServiceName == "" { return true } return !lo.SomeBy(gui.Panels.Services.List.GetAllItems(), func(service *commands.Service) bool { return service.Name == container.ServiceName }) } return &panels.SideListPanel[*commands.Container]{ ContextState: &panels.ContextState[*commands.Container]{ GetMainTabs: func() []panels.MainTab[*commands.Container] { return []panels.MainTab[*commands.Container]{ { Key: "logs", Title: gui.Tr.LogsTitle, Render: gui.renderContainerLogsToMain, }, { Key: "stats", Title: gui.Tr.StatsTitle, Render: gui.renderContainerStats, }, { Key: "env", Title: gui.Tr.EnvTitle, Render: gui.renderContainerEnv, }, { Key: "config", Title: gui.Tr.ConfigTitle, Render: gui.renderContainerConfig, }, { Key: "top", Title: gui.Tr.TopTitle, Render: gui.renderContainerTop, }, } }, GetItemContextCacheKey: func(container *commands.Container) string { // Including the container state in the cache key so that if the container // restarts we re-read the logs. In the past we've had some glitchiness // where a container restarts but the new logs don't get read. // Note that this might be jarring if we have a lot of logs and the container // restarts a lot, so let's keep an eye on it. return "containers-" + container.ID + "-" + container.Container.State }, }, ListPanel: panels.ListPanel[*commands.Container]{ List: panels.NewFilteredList[*commands.Container](), View: gui.Views.Containers, }, NoItemsMessage: gui.Tr.NoContainers, Gui: gui.intoInterface(), // sortedContainers returns containers sorted by state if c.SortContainersByState is true (follows 1- running, 2- exited, 3- created) // and sorted by name if c.SortContainersByState is false Sort: func(a *commands.Container, b *commands.Container) bool { return sortContainers(a, b, gui.Config.UserConfig.Gui.LegacySortContainers) }, Filter: func(container *commands.Container) bool { // Note that this is O(N*M) time complexity where N is the number of services // and M is the number of containers. We expect N to be small but M may be large, // so we will need to keep an eye on this. if !gui.Config.UserConfig.Gui.ShowAllContainers && !isStandaloneContainer(container) { return false } if !gui.State.ShowExitedContainers && container.Container.State == "exited" { return false } return true }, GetTableCells: func(container *commands.Container) []string { return presentation.GetContainerDisplayStrings(&gui.Config.UserConfig.Gui, container) }, } } var containerStates = map[string]int{ "running": 1, "exited": 2, "created": 3, } func sortContainers(a *commands.Container, b *commands.Container, legacySort bool) bool { if legacySort { return a.Name < b.Name } stateLeft := containerStates[a.Container.State] stateRight := containerStates[b.Container.State] if stateLeft == stateRight { return a.Name < b.Name } return containerStates[a.Container.State] < containerStates[b.Container.State] } func (gui *Gui) renderContainerEnv(container *commands.Container) tasks.TaskFunc { return gui.NewSimpleRenderStringTask(func() string { return gui.containerEnv(container) }) } func (gui *Gui) containerEnv(container *commands.Container) string { if !container.DetailsLoaded() { return gui.Tr.WaitingForContainerInfo } if len(container.Details.Config.Env) == 0 { return gui.Tr.NothingToDisplay } envVarsList := lo.Map(container.Details.Config.Env, func(envVar string, _ int) []string { splitEnv := strings.SplitN(envVar, "=", 2) key := splitEnv[0] value := "" if len(splitEnv) > 1 { value = splitEnv[1] } return []string{ utils.ColoredString(key+":", color.FgGreen), utils.ColoredString(value, color.FgYellow), } }) output, err := utils.RenderTable(envVarsList) if err != nil { gui.Log.Error(err) return gui.Tr.CannotDisplayEnvVariables } return output } func (gui *Gui) renderContainerConfig(container *commands.Container) tasks.TaskFunc { return gui.NewSimpleRenderStringTask(func() string { return gui.containerConfigStr(container) }) } func (gui *Gui) containerConfigStr(container *commands.Container) string { if !container.DetailsLoaded() { return gui.Tr.WaitingForContainerInfo } padding := 10 output := "" output += utils.WithPadding("ID: ", padding) + container.ID + "\n" output += utils.WithPadding("Name: ", padding) + container.Name + "\n" output += utils.WithPadding("Image: ", padding) + container.Details.Config.Image + "\n" output += utils.WithPadding("Command: ", padding) + strings.Join(append([]string{container.Details.Path}, container.Details.Args...), " ") + "\n" output += utils.WithPadding("Labels: ", padding) + utils.FormatMap(padding, container.Details.Config.Labels) output += "\n" output += utils.WithPadding("Mounts: ", padding) if len(container.Details.Mounts) > 0 { output += "\n" for _, mount := range container.Details.Mounts { if mount.Type == "volume" { output += fmt.Sprintf("%s%s %s\n", strings.Repeat(" ", padding), utils.ColoredString(string(mount.Type)+":", color.FgYellow), mount.Name) } else { output += fmt.Sprintf("%s%s %s:%s\n", strings.Repeat(" ", padding), utils.ColoredString(string(mount.Type)+":", color.FgYellow), mount.Source, mount.Destination) } } } else { output += "none\n" } output += utils.WithPadding("Ports: ", padding) if len(container.Details.NetworkSettings.Ports) > 0 { output += "\n" for k, v := range container.Details.NetworkSettings.Ports { for _, host := range v { output += fmt.Sprintf("%s%s %s\n", strings.Repeat(" ", padding), utils.ColoredString(host.HostPort+":", color.FgYellow), k) } } } else { output += "none\n" } data, err := utils.MarshalIntoYaml(&container.Details) if err != nil { return fmt.Sprintf("Error marshalling container details: %v", err) } output += fmt.Sprintf("\nFull details:\n\n%s", utils.ColoredYamlString(string(data))) return output } func (gui *Gui) renderContainerStats(container *commands.Container) tasks.TaskFunc { return gui.NewTickerTask(TickerTaskOpts{ Func: func(ctx context.Context, notifyStopped chan struct{}) { contents, err := presentation.RenderStats(gui.Config.UserConfig, container, gui.Views.Main.Width()) if err != nil { _ = gui.createErrorPanel(err.Error()) } gui.reRenderStringMain(contents) }, Duration: time.Second, Before: func(ctx context.Context) { gui.clearMainView() }, Wrap: false, // wrapping looks bad here so we're overriding the config value Autoscroll: false, }) } func (gui *Gui) renderContainerTop(container *commands.Container) tasks.TaskFunc { return gui.NewTickerTask(TickerTaskOpts{ Func: func(ctx context.Context, notifyStopped chan struct{}) { contents, err := container.RenderTop(ctx) if err != nil { gui.RenderStringMain(err.Error()) } gui.reRenderStringMain(contents) }, Duration: time.Second, Before: func(ctx context.Context) { gui.clearMainView() }, Wrap: gui.Config.UserConfig.Gui.WrapMainPanel, Autoscroll: false, }) } func (gui *Gui) refreshContainersAndServices() error { if gui.Views.Containers == nil { // if the containersView hasn't been instantiated yet we just return return nil } // keep track of current service selected so that we can reposition our cursor if it moves position in the list originalSelectedLineIdx := gui.Panels.Services.SelectedIdx selectedService, isServiceSelected := gui.Panels.Services.List.TryGet(originalSelectedLineIdx) containers, services, err := gui.DockerCommand.RefreshContainersAndServices( gui.Panels.Services.List.GetAllItems(), gui.Panels.Containers.List.GetAllItems(), ) if err != nil { return err } gui.Panels.Services.SetItems(services) gui.Panels.Containers.SetItems(containers) // see if our selected service has moved if isServiceSelected { for i, service := range gui.Panels.Services.List.GetItems() { if service.ID == selectedService.ID { if i == originalSelectedLineIdx { break } gui.Panels.Services.SetSelectedLineIdx(i) gui.Panels.Services.Refocus() } } } return gui.renderContainersAndServices() } func (gui *Gui) renderContainersAndServices() error { if gui.DockerCommand.InDockerComposeProject { if err := gui.Panels.Services.RerenderList(); err != nil { return err } } if err := gui.Panels.Containers.RerenderList(); err != nil { return err } return nil } func (gui *Gui) handleHideStoppedContainers(g *gocui.Gui, v *gocui.View) error { gui.State.ShowExitedContainers = !gui.State.ShowExitedContainers return gui.Panels.Containers.RerenderList() } func (gui *Gui) handleContainersRemoveMenu(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } handleMenuPress := func(configOptions container.RemoveOptions) error { return gui.WithWaitingStatus(gui.Tr.RemovingStatus, func() error { if err := ctr.Remove(configOptions); err != nil { if commands.HasErrorCode(err, commands.MustStopContainer) { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.MustForceToRemoveContainer, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.RemovingStatus, func() error { configOptions.Force = true return ctr.Remove(configOptions) }) }, nil) } return gui.createErrorPanel(err.Error()) } return nil }) } menuItems := []*types.MenuItem{ { LabelColumns: []string{gui.Tr.Remove, "docker rm " + ctr.ID[1:10]}, OnPress: func() error { return handleMenuPress(container.RemoveOptions{}) }, }, { LabelColumns: []string{gui.Tr.RemoveWithVolumes, "docker rm --volumes " + ctr.ID[1:10]}, OnPress: func() error { return handleMenuPress(container.RemoveOptions{RemoveVolumes: true}) }, }, } return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) PauseContainer(container *commands.Container) error { return gui.WithWaitingStatus(gui.Tr.PausingStatus, func() (err error) { if container.Details.State.Paused { err = container.Unpause() } else { err = container.Pause() } if err != nil { return gui.createErrorPanel(err.Error()) } return gui.refreshContainersAndServices() }) } func (gui *Gui) handleContainerPause(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } return gui.PauseContainer(ctr) } func (gui *Gui) handleContainerStop(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.StopContainer, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.StoppingStatus, func() error { if err := ctr.Stop(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, nil) } func (gui *Gui) handleContainerRestart(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } return gui.WithWaitingStatus(gui.Tr.RestartingStatus, func() error { if err := ctr.Restart(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) } func (gui *Gui) handleContainerAttach(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } c, err := ctr.Attach() if err != nil { return gui.createErrorPanel(err.Error()) } return gui.runSubprocessWithMessage(c, gui.Tr.DetachFromContainerShortCut) } func (gui *Gui) handlePruneContainers() error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmPruneContainers, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.PruningStatus, func() error { err := gui.DockerCommand.PruneContainers() if err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, nil) } func (gui *Gui) handleContainerViewLogs(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } gui.renderLogsToStdout(ctr) return nil } func (gui *Gui) handleContainersExecShell(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } return gui.containerExecShell(ctr) } func (gui *Gui) containerExecShell(container *commands.Container) error { commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{ Container: container, }) // TODO: use SDK resolvedCommand := utils.ApplyTemplate("docker exec -it {{ .Container.ID }} /bin/sh -c 'eval $(grep ^$(id -un): /etc/passwd | cut -d : -f 7-)'", commandObject) // attach and return the subprocess error cmd := gui.OSCommand.ExecutableFromString(resolvedCommand) return gui.runSubprocess(cmd) } func (gui *Gui) handleContainersCustomCommand(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{ Container: ctr, }) customCommands := gui.Config.UserConfig.CustomCommands.Containers return gui.createCustomCommandMenu(customCommands, commandObject) } func (gui *Gui) handleStopContainers() error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmStopContainers, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.StoppingStatus, func() error { for _, ctr := range gui.Panels.Containers.List.GetAllItems() { if err := ctr.Stop(); err != nil { gui.Log.Error(err) } } return nil }) }, nil) } func (gui *Gui) handleRemoveContainers() error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmRemoveContainers, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.RemovingStatus, func() error { for _, ctr := range gui.Panels.Containers.List.GetAllItems() { if err := ctr.Remove(container.RemoveOptions{Force: true}); err != nil { gui.Log.Error(err) } } return nil }) }, nil) } func (gui *Gui) handleContainersBulkCommand(g *gocui.Gui, v *gocui.View) error { baseBulkCommands := []config.CustomCommand{ { Name: gui.Tr.StopAllContainers, InternalFunction: gui.handleStopContainers, }, { Name: gui.Tr.RemoveAllContainers, InternalFunction: gui.handleRemoveContainers, }, { Name: gui.Tr.PruneContainers, InternalFunction: gui.handlePruneContainers, }, } bulkCommands := append(baseBulkCommands, gui.Config.UserConfig.BulkCommands.Containers...) commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{}) return gui.createBulkCommandMenu(bulkCommands, commandObject) } // Open first port in browser func (gui *Gui) handleContainersOpenInBrowserCommand(g *gocui.Gui, v *gocui.View) error { ctr, err := gui.Panels.Containers.GetSelectedItem() if err != nil { return nil } return gui.openContainerInBrowser(ctr) } func (gui *Gui) openContainerInBrowser(ctr *commands.Container) error { // skip if no any ports if len(ctr.Container.Ports) == 0 { return nil } // skip if the first port is not published port := ctr.Container.Ports[0] if port.IP == "" { return nil } ip := port.IP if ip == "0.0.0.0" { ip = "localhost" } link := fmt.Sprintf("http://%s:%d/", ip, port.PublicPort) return gui.OSCommand.OpenLink(link) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/confirmation_panel.go
pkg/gui/confirmation_panel.go
// lots of this has been directly ported from one of the example files, will brush up later // Copyright 2014 The gocui Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gui import ( "strings" "github.com/fatih/color" "github.com/jesseduffield/gocui" ) func (gui *Gui) wrappedConfirmationFunction(function func(*gocui.Gui, *gocui.View) error) func(*gocui.Gui, *gocui.View) error { return func(g *gocui.Gui, v *gocui.View) error { if err := gui.closeConfirmationPrompt(); err != nil { return err } if function != nil { if err := function(g, v); err != nil { return err } } return nil } } func (gui *Gui) closeConfirmationPrompt() error { if err := gui.returnFocus(); err != nil { return err } gui.g.DeleteViewKeybindings("confirmation") gui.Views.Confirmation.Visible = false return nil } func (gui *Gui) getMessageHeight(wrap bool, message string, width int) int { lines := strings.Split(message, "\n") lineCount := 0 // if we need to wrap, calculate height to fit content within view's width if wrap { for _, line := range lines { lineCount += len(line)/width + 1 } } else { lineCount = len(lines) } return lineCount } func (gui *Gui) getConfirmationPanelDimensions(wrap bool, prompt string) (int, int, int, int) { width, height := gui.g.Size() panelWidth := width / 2 panelHeight := gui.getMessageHeight(wrap, prompt, panelWidth) return width/2 - panelWidth/2, height/2 - panelHeight/2 - panelHeight%2 - 1, width/2 + panelWidth/2, height/2 + panelHeight/2 } func (gui *Gui) createPromptPanel(title string, handleConfirm func(*gocui.Gui, *gocui.View) error) error { gui.onNewPopupPanel() err := gui.prepareConfirmationPanel(title, "") if err != nil { return err } gui.Views.Confirmation.Editable = true return gui.setKeyBindings(gui.g, handleConfirm, nil) } func (gui *Gui) prepareConfirmationPanel(title, prompt string) error { x0, y0, x1, y1 := gui.getConfirmationPanelDimensions(true, prompt) confirmationView := gui.Views.Confirmation _, err := gui.g.SetView("confirmation", x0, y0, x1, y1, 0) if err != nil { return err } confirmationView.Title = title confirmationView.Visible = true gui.g.Update(func(g *gocui.Gui) error { return gui.switchFocus(confirmationView) }) return nil } func (gui *Gui) onNewPopupPanel() { gui.Views.Menu.Visible = false gui.Views.Confirmation.Visible = false } // It is very important that within this function we never include the original prompt in any error messages, because it may contain e.g. a user password. // The golangcilint unparam linter complains that handleClose is alwans nil but one day it won't be nil. // nolint:unparam func (gui *Gui) createConfirmationPanel(title, prompt string, handleConfirm, handleClose func(*gocui.Gui, *gocui.View) error) error { return gui.createPopupPanel(title, prompt, handleConfirm, handleClose) } func (gui *Gui) createPopupPanel(title, prompt string, handleConfirm, handleClose func(*gocui.Gui, *gocui.View) error) error { gui.onNewPopupPanel() gui.g.Update(func(g *gocui.Gui) error { if gui.currentViewName() == "confirmation" { if err := gui.closeConfirmationPrompt(); err != nil { gui.Log.Error(err.Error()) } } err := gui.prepareConfirmationPanel(title, prompt) if err != nil { return err } gui.Views.Confirmation.Editable = false if err := gui.renderString(g, "confirmation", prompt); err != nil { return err } return gui.setKeyBindings(g, handleConfirm, handleClose) }) return nil } func (gui *Gui) setKeyBindings(g *gocui.Gui, handleConfirm, handleClose func(*gocui.Gui, *gocui.View) error) error { // would use a loop here but because the function takes an interface{} and slices of interfaces require even more boilerplate if err := g.SetKeybinding("confirmation", gocui.KeyEnter, gocui.ModNone, gui.wrappedConfirmationFunction(handleConfirm)); err != nil { return err } if err := g.SetKeybinding("confirmation", 'y', gocui.ModNone, gui.wrappedConfirmationFunction(handleConfirm)); err != nil { return err } if err := g.SetKeybinding("confirmation", gocui.KeyEsc, gocui.ModNone, gui.wrappedConfirmationFunction(handleClose)); err != nil { return err } if err := g.SetKeybinding("confirmation", 'n', gocui.ModNone, gui.wrappedConfirmationFunction(handleClose)); err != nil { return err } return nil } func (gui *Gui) createErrorPanel(message string) error { colorFunction := color.New(color.FgRed).SprintFunc() coloredMessage := colorFunction(strings.TrimSpace(message)) return gui.createConfirmationPanel(gui.Tr.ErrorTitle, coloredMessage, nil, nil) } func (gui *Gui) renderConfirmationOptions() error { optionsMap := map[string]string{ "n/esc": gui.Tr.No, "y/enter": gui.Tr.Yes, } return gui.renderOptionsMap(optionsMap) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/layout.go
pkg/gui/layout.go
package gui import ( "github.com/jesseduffield/gocui" ) const UNKNOWN_VIEW_ERROR_MSG = "unknown view" // getFocusLayout returns a manager function for when view gain and lose focus func (gui *Gui) getFocusLayout() func(g *gocui.Gui) error { var previousView *gocui.View return func(g *gocui.Gui) error { newView := gui.g.CurrentView() if err := gui.onFocusChange(); err != nil { return err } // for now we don't consider losing focus to a popup panel as actually losing focus if newView != previousView && !gui.isPopupPanel(newView.Name()) { gui.onFocusLost(previousView, newView) gui.onFocus(newView) previousView = newView } return nil } } func (gui *Gui) onFocusChange() error { currentView := gui.g.CurrentView() for _, view := range gui.g.Views() { view.Highlight = view == currentView && view.Name() != "main" } return nil } func (gui *Gui) onFocusLost(v *gocui.View, newView *gocui.View) { if v == nil { return } if !gui.isPopupPanel(newView.Name()) { v.ParentView = nil } // refocusing because in responsive mode (when the window is very short) we want to ensure that after the view size changes we can still see the last selected item gui.focusPointInView(v) gui.Log.Info(v.Name() + " focus lost") } func (gui *Gui) onFocus(v *gocui.View) { if v == nil { return } gui.focusPointInView(v) gui.Log.Info(v.Name() + " focus gained") } // layout is called for every screen re-render e.g. when the screen is resized func (gui *Gui) layout(g *gocui.Gui) error { g.Highlight = true width, height := g.Size() appStatus := gui.statusManager.getStatusString() viewDimensions := gui.getWindowDimensions(gui.getInformationContent(), appStatus) // we assume that the view has already been created. setViewFromDimensions := func(viewName string, windowName string) (*gocui.View, error) { dimensionsObj, ok := viewDimensions[windowName] view, err := g.View(viewName) if err != nil { return nil, err } if !ok { // view not specified in dimensions object: so create the view and hide it // making the view take up the whole space in the background in case it needs // to render content as soon as it appears, because lazyloaded content (via a pty task) // cares about the size of the view. _, err := g.SetView(viewName, 0, 0, width, height, 0) view.Visible = false return view, err } frameOffset := 1 if view.Frame { frameOffset = 0 } _, err = g.SetView( viewName, dimensionsObj.X0-frameOffset, dimensionsObj.Y0-frameOffset, dimensionsObj.X1+frameOffset, dimensionsObj.Y1+frameOffset, 0, ) view.Visible = true return view, err } for _, viewName := range gui.autoPositionedViewNames() { _, err := setViewFromDimensions(viewName, viewName) if err != nil && err.Error() != UNKNOWN_VIEW_ERROR_MSG { return err } } // here is a good place log some stuff // if you download humanlog and do tail -f development.log | humanlog // this will let you see these branches as prettified json // gui.Log.Info(utils.AsJson(gui.State.Branches[0:4])) return gui.resizeCurrentPopupPanel(g) } func (gui *Gui) focusPointInView(view *gocui.View) { if view == nil { return } currentPanel, ok := gui.currentListPanel() if ok { currentPanel.Refocus() } } func (gui *Gui) prepareView(viewName string) (*gocui.View, error) { // arbitrarily giving the view enough size so that we don't get an error, but // it's expected that the view will be given the correct size before being shown return gui.g.SetView(viewName, 0, 0, 10, 10, 0) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/images_panel.go
pkg/gui/images_panel.go
package gui import ( "fmt" "strings" "time" "github.com/docker/docker/api/types/image" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) getImagesPanel() *panels.SideListPanel[*commands.Image] { noneLabel := "<none>" return &panels.SideListPanel[*commands.Image]{ ContextState: &panels.ContextState[*commands.Image]{ GetMainTabs: func() []panels.MainTab[*commands.Image] { return []panels.MainTab[*commands.Image]{ { Key: "config", Title: gui.Tr.ConfigTitle, Render: gui.renderImageConfigTask, }, } }, GetItemContextCacheKey: func(image *commands.Image) string { return "images-" + image.ID }, }, ListPanel: panels.ListPanel[*commands.Image]{ List: panels.NewFilteredList[*commands.Image](), View: gui.Views.Images, }, NoItemsMessage: gui.Tr.NoImages, Gui: gui.intoInterface(), Sort: func(a *commands.Image, b *commands.Image) bool { if a.Name == noneLabel && b.Name != noneLabel { return false } if a.Name != noneLabel && b.Name == noneLabel { return true } if a.Name != b.Name { return a.Name < b.Name } if a.Tag != b.Tag { return a.Tag < b.Tag } return a.ID < b.ID }, GetTableCells: presentation.GetImageDisplayStrings, } } func (gui *Gui) renderImageConfigTask(image *commands.Image) tasks.TaskFunc { return gui.NewRenderStringTask(RenderStringTaskOpts{ GetStrContent: func() string { return gui.imageConfigStr(image) }, Autoscroll: false, Wrap: false, // don't care what your config is this page is ugly without wrapping }) } func (gui *Gui) imageConfigStr(image *commands.Image) string { padding := 10 output := "" output += utils.WithPadding("Name: ", padding) + image.Name + "\n" output += utils.WithPadding("ID: ", padding) + image.Image.ID + "\n" output += utils.WithPadding("Tags: ", padding) + utils.ColoredString(strings.Join(image.Image.RepoTags, ", "), color.FgGreen) + "\n" output += utils.WithPadding("Size: ", padding) + utils.FormatDecimalBytes(int(image.Image.Size)) + "\n" output += utils.WithPadding("Created: ", padding) + fmt.Sprintf("%v", time.Unix(image.Image.Created, 0).Format(time.RFC1123)) + "\n" history, err := image.RenderHistory() if err != nil { gui.Log.Error(err) } output += "\n\n" + history return output } func (gui *Gui) reloadImages() error { if err := gui.refreshStateImages(); err != nil { return err } return gui.Panels.Images.RerenderList() } func (gui *Gui) refreshStateImages() error { images, err := gui.DockerCommand.RefreshImages() if err != nil { return err } gui.Panels.Images.SetItems(images) return nil } func (gui *Gui) FilterString(view *gocui.View) string { if gui.State.Filter.panel != nil && gui.State.Filter.panel.GetView() != view { return "" } return gui.State.Filter.needle } func (gui *Gui) handleImagesRemoveMenu(g *gocui.Gui, v *gocui.View) error { type removeImageOption struct { description string command string configOptions image.RemoveOptions } img, err := gui.Panels.Images.GetSelectedItem() if err != nil { return nil } shortSha := img.ID[7:17] // TODO: have a way of toggling in a menu instead of showing each permutation as a separate menu item options := []*removeImageOption{ { description: gui.Tr.Remove, command: "docker image rm " + shortSha, configOptions: image.RemoveOptions{PruneChildren: true, Force: false}, }, { description: gui.Tr.RemoveWithoutPrune, command: "docker image rm --no-prune " + shortSha, configOptions: image.RemoveOptions{PruneChildren: false, Force: false}, }, { description: gui.Tr.RemoveWithForce, command: "docker image rm --force " + shortSha, configOptions: image.RemoveOptions{PruneChildren: true, Force: true}, }, { description: gui.Tr.RemoveWithoutPruneWithForce, command: "docker image rm --no-prune --force " + shortSha, configOptions: image.RemoveOptions{PruneChildren: false, Force: true}, }, } menuItems := lo.Map(options, func(option *removeImageOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{ option.description, color.New(color.FgRed).Sprint(option.command), }, OnPress: func() error { if err := img.Remove(option.configOptions); err != nil { return gui.createErrorPanel(err.Error()) } return nil }, } }) return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) handlePruneImages() error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmPruneImages, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.PruningStatus, func() error { err := gui.DockerCommand.PruneImages() if err != nil { return gui.createErrorPanel(err.Error()) } return gui.reloadImages() }) }, nil) } func (gui *Gui) handleImagesCustomCommand(g *gocui.Gui, v *gocui.View) error { img, err := gui.Panels.Images.GetSelectedItem() if err != nil { return nil } commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{ Image: img, }) customCommands := gui.Config.UserConfig.CustomCommands.Images return gui.createCustomCommandMenu(customCommands, commandObject) } func (gui *Gui) handleImagesBulkCommand(g *gocui.Gui, v *gocui.View) error { baseBulkCommands := []config.CustomCommand{ { Name: gui.Tr.PruneImages, InternalFunction: gui.handlePruneImages, }, } bulkCommands := append(baseBulkCommands, gui.Config.UserConfig.BulkCommands.Images...) commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{}) return gui.createBulkCommandMenu(bulkCommands, commandObject) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/focus.go
pkg/gui/focus.go
package gui import ( "github.com/jesseduffield/gocui" "github.com/samber/lo" ) func (gui *Gui) newLineFocused(v *gocui.View) error { if v == nil { return nil } currentListPanel, ok := gui.currentListPanel() if ok { return currentListPanel.HandleSelect() } switch v.Name() { case "confirmation": return nil case "main": v.Highlight = false return nil case "filter": return nil default: panic(gui.Tr.NoViewMachingNewLineFocusedSwitchStatement) } } // TODO: move some of this logic into our onFocusLost and onFocus hooks func (gui *Gui) switchFocus(newView *gocui.View) error { gui.Mutexes.ViewStackMutex.Lock() defer gui.Mutexes.ViewStackMutex.Unlock() return gui.switchFocusAux(newView) } func (gui *Gui) switchFocusAux(newView *gocui.View) error { gui.pushView(newView.Name()) gui.Log.Info("setting highlight to true for view " + newView.Name()) gui.Log.Info("new focused view is " + newView.Name()) if _, err := gui.g.SetCurrentView(newView.Name()); err != nil { return err } gui.g.Cursor = newView.Editable if err := gui.renderPanelOptions(); err != nil { return err } newViewStack := gui.State.ViewStack if gui.State.Filter.panel != nil && !lo.Contains(newViewStack, gui.State.Filter.panel.GetView().Name()) { if err := gui.clearFilter(); err != nil { return err } } // TODO: add 'onFocusLost' hook if !lo.Contains(newViewStack, "menu") { gui.Views.Menu.Visible = false } return gui.newLineFocused(newView) } func (gui *Gui) returnFocus() error { gui.Mutexes.ViewStackMutex.Lock() defer gui.Mutexes.ViewStackMutex.Unlock() if len(gui.State.ViewStack) <= 1 { return nil } previousViewName := gui.State.ViewStack[len(gui.State.ViewStack)-2] previousView, err := gui.g.View(previousViewName) if err != nil { return err } return gui.switchFocusAux(previousView) } func (gui *Gui) removeViewFromStack(view *gocui.View) { gui.Mutexes.ViewStackMutex.Lock() defer gui.Mutexes.ViewStackMutex.Unlock() gui.State.ViewStack = lo.Filter(gui.State.ViewStack, func(viewName string, _ int) bool { return viewName != view.Name() }) } // Not to be called directly. Use `switchFocus` instead func (gui *Gui) pushView(name string) { // No matter what view we're pushing, we first remove all popup panels from the stack // (unless it's the search view because we may be searching the menu panel) if name != "filter" { gui.State.ViewStack = lo.Filter(gui.State.ViewStack, func(viewName string, _ int) bool { return !gui.isPopupPanel(viewName) }) } // If we're pushing a side panel, we remove all other panels if lo.Contains(gui.sideViewNames(), name) { gui.State.ViewStack = []string{} } // If we're pushing a panel that's already in the stack, we remove it gui.State.ViewStack = lo.Filter(gui.State.ViewStack, func(viewName string, _ int) bool { return viewName != name }) gui.State.ViewStack = append(gui.State.ViewStack, name) } // excludes popups func (gui *Gui) currentStaticViewName() string { gui.Mutexes.ViewStackMutex.Lock() defer gui.Mutexes.ViewStackMutex.Unlock() for i := len(gui.State.ViewStack) - 1; i >= 0; i-- { if !lo.Contains(gui.popupViewNames(), gui.State.ViewStack[i]) { return gui.State.ViewStack[i] } } return gui.initiallyFocusedViewName() } func (gui *Gui) currentSideViewName() string { gui.Mutexes.ViewStackMutex.Lock() defer gui.Mutexes.ViewStackMutex.Unlock() // we expect that there is a side window somewhere in the view stack, so we will search from top to bottom for idx := range gui.State.ViewStack { reversedIdx := len(gui.State.ViewStack) - 1 - idx viewName := gui.State.ViewStack[reversedIdx] if lo.Contains(gui.sideViewNames(), viewName) { return viewName } } return gui.initiallyFocusedViewName() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/menu_panel.go
pkg/gui/menu_panel.go
package gui import ( "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/utils" ) type CreateMenuOptions struct { Title string Items []*types.MenuItem HideCancel bool } func (gui *Gui) getMenuPanel() *panels.SideListPanel[*types.MenuItem] { return &panels.SideListPanel[*types.MenuItem]{ ListPanel: panels.ListPanel[*types.MenuItem]{ List: panels.NewFilteredList[*types.MenuItem](), View: gui.Views.Menu, }, NoItemsMessage: "", Gui: gui.intoInterface(), OnClick: gui.onMenuPress, Sort: nil, GetTableCells: presentation.GetMenuItemDisplayStrings, OnRerender: func() error { return gui.resizePopupPanel(gui.Views.Menu) }, // so that we can avoid some UI trickiness, the menu will not have filtering // abillity yet. To support it, we would need to have filter state against // each panel (e.g. for when you filter the images panel, then bring up // the options menu, then try to filter that too. DisableFilter: true, } } func (gui *Gui) onMenuPress(menuItem *types.MenuItem) error { if err := gui.handleMenuClose(); err != nil { return err } if menuItem.OnPress != nil { return menuItem.OnPress() } return nil } func (gui *Gui) handleMenuPress() error { selectedMenuItem, err := gui.Panels.Menu.GetSelectedItem() if err != nil { return nil } return gui.onMenuPress(selectedMenuItem) } func (gui *Gui) Menu(opts CreateMenuOptions) error { if !opts.HideCancel { // this is mutative but I'm okay with that for now opts.Items = append(opts.Items, &types.MenuItem{ LabelColumns: []string{gui.Tr.Cancel}, OnPress: func() error { return nil }, }) } maxColumnSize := 1 for _, item := range opts.Items { if item.LabelColumns == nil { item.LabelColumns = []string{item.Label} } if item.OpensMenu { item.LabelColumns[0] = utils.OpensMenuStyle(item.LabelColumns[0]) } maxColumnSize = utils.Max(maxColumnSize, len(item.LabelColumns)) } for _, item := range opts.Items { if len(item.LabelColumns) < maxColumnSize { // we require that each item has the same number of columns so we're padding out with blank strings // if this item has too few item.LabelColumns = append(item.LabelColumns, make([]string, maxColumnSize-len(item.LabelColumns))...) } } gui.Panels.Menu.SetItems(opts.Items) gui.Panels.Menu.SetSelectedLineIdx(0) if err := gui.Panels.Menu.RerenderList(); err != nil { return err } gui.Views.Menu.Title = opts.Title gui.Views.Menu.Visible = true return gui.switchFocus(gui.Views.Menu) } // specific functions func (gui *Gui) renderMenuOptions() error { optionsMap := map[string]string{ "esc": gui.Tr.Close, "↑ ↓": gui.Tr.Navigate, "enter": gui.Tr.Execute, } return gui.renderOptionsMap(optionsMap) } func (gui *Gui) handleMenuClose() error { gui.Views.Menu.Visible = false // this code is here for when we do add filter ability to the menu panel, // though it's currently disabled if gui.State.Filter.panel == gui.Panels.Menu { if err := gui.clearFilter(); err != nil { return err } // we need to remove the view from the view stack because we're about to // return focus and don't want to land in the search view when it was searching // the menu in the first place gui.removeViewFromStack(gui.Views.Filter) } return gui.returnFocus() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/panels.go
pkg/gui/panels.go
package gui import "github.com/jesseduffield/lazydocker/pkg/gui/panels" func (gui *Gui) intoInterface() panels.IGui { return gui }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/services_panel.go
pkg/gui/services_panel.go
package gui import ( "context" "fmt" "time" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) getServicesPanel() *panels.SideListPanel[*commands.Service] { return &panels.SideListPanel[*commands.Service]{ ContextState: &panels.ContextState[*commands.Service]{ GetMainTabs: func() []panels.MainTab[*commands.Service] { return []panels.MainTab[*commands.Service]{ { Key: "logs", Title: gui.Tr.LogsTitle, Render: gui.renderServiceLogs, }, { Key: "stats", Title: gui.Tr.StatsTitle, Render: gui.renderServiceStats, }, { Key: "container-env", Title: gui.Tr.ContainerEnvTitle, Render: gui.renderServiceContainerEnv, }, { Key: "container-config", Title: gui.Tr.ContainerConfigTitle, Render: gui.renderServiceContainerConfig, }, { Key: "top", Title: gui.Tr.TopTitle, Render: gui.renderServiceTop, }, } }, GetItemContextCacheKey: func(service *commands.Service) string { if service.Container == nil { return "services-" + service.ID } return "services-" + service.ID + "-" + service.Container.ID + "-" + service.Container.Container.State }, }, ListPanel: panels.ListPanel[*commands.Service]{ List: panels.NewFilteredList[*commands.Service](), View: gui.Views.Services, }, NoItemsMessage: gui.Tr.NoServices, Gui: gui.intoInterface(), // sort services first by whether they have a linked container, and second by alphabetical order Sort: func(a *commands.Service, b *commands.Service) bool { if a.Container != nil && b.Container == nil { return true } if a.Container == nil && b.Container != nil { return false } return a.Name < b.Name }, GetTableCells: func(service *commands.Service) []string { return presentation.GetServiceDisplayStrings(&gui.Config.UserConfig.Gui, service) }, Hide: func() bool { return !gui.DockerCommand.InDockerComposeProject }, } } func (gui *Gui) renderServiceContainerConfig(service *commands.Service) tasks.TaskFunc { if service.Container == nil { return gui.NewSimpleRenderStringTask(func() string { return gui.Tr.NoContainer }) } return gui.renderContainerConfig(service.Container) } func (gui *Gui) renderServiceContainerEnv(service *commands.Service) tasks.TaskFunc { if service.Container == nil { return gui.NewSimpleRenderStringTask(func() string { return gui.Tr.NoContainer }) } return gui.renderContainerEnv(service.Container) } func (gui *Gui) renderServiceStats(service *commands.Service) tasks.TaskFunc { if service.Container == nil { return gui.NewSimpleRenderStringTask(func() string { return gui.Tr.NoContainer }) } return gui.renderContainerStats(service.Container) } func (gui *Gui) renderServiceTop(service *commands.Service) tasks.TaskFunc { return gui.NewTickerTask(TickerTaskOpts{ Func: func(ctx context.Context, notifyStopped chan struct{}) { contents, err := service.RenderTop(ctx) if err != nil { gui.RenderStringMain(err.Error()) } gui.reRenderStringMain(contents) }, Duration: time.Second, Before: func(ctx context.Context) { gui.clearMainView() }, Wrap: gui.Config.UserConfig.Gui.WrapMainPanel, Autoscroll: false, }) } func (gui *Gui) renderServiceLogs(service *commands.Service) tasks.TaskFunc { if service.Container == nil { return gui.NewSimpleRenderStringTask(func() string { return gui.Tr.NoContainerForService }) } return gui.renderContainerLogsToMain(service.Container) } type commandOption struct { description string command string onPress func() error } func (r *commandOption) getDisplayStrings() []string { return []string{r.description, color.New(color.FgCyan).Sprint(r.command)} } func (gui *Gui) handleServiceRemoveMenu(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } composeCommand := gui.Config.UserConfig.CommandTemplates.DockerCompose options := []*commandOption{ { description: gui.Tr.Remove, command: fmt.Sprintf("%s rm --stop --force %s", composeCommand, service.Name), }, { description: gui.Tr.RemoveWithVolumes, command: fmt.Sprintf("%s rm --stop --force -v %s", composeCommand, service.Name), }, } menuItems := lo.Map(options, func(option *commandOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: option.getDisplayStrings(), OnPress: func() error { return gui.WithWaitingStatus(gui.Tr.RemovingStatus, func() error { if err := gui.OSCommand.RunCommand(option.command); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, } }) return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) handleServicePause(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } if service.Container == nil { return nil } return gui.PauseContainer(service.Container) } func (gui *Gui) handleServiceStop(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.StopService, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.StoppingStatus, func() error { if err := service.Stop(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, nil) } func (gui *Gui) handleServiceUp(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } return gui.WithWaitingStatus(gui.Tr.UppingServiceStatus, func() error { if err := service.Up(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) } func (gui *Gui) handleServiceRestart(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } return gui.WithWaitingStatus(gui.Tr.RestartingStatus, func() error { if err := service.Restart(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) } func (gui *Gui) handleServiceStart(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } return gui.WithWaitingStatus(gui.Tr.StartingStatus, func() error { if err := service.Start(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) } func (gui *Gui) handleServiceAttach(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } if service.Container == nil { return gui.createErrorPanel(gui.Tr.NoContainers) } c, err := service.Attach() if err != nil { return gui.createErrorPanel(err.Error()) } return gui.runSubprocess(c) } func (gui *Gui) handleServiceRenderLogsToMain(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } c, err := service.ViewLogs() if err != nil { return gui.createErrorPanel(err.Error()) } return gui.runSubprocess(c) } func (gui *Gui) handleProjectUp(g *gocui.Gui, v *gocui.View) error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmUpProject, func(g *gocui.Gui, v *gocui.View) error { cmdStr := utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.Up, gui.DockerCommand.NewCommandObject(commands.CommandObject{}), ) return gui.WithWaitingStatus(gui.Tr.UppingProjectStatus, func() error { if err := gui.OSCommand.RunCommand(cmdStr); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, nil) } func (gui *Gui) handleProjectDown(g *gocui.Gui, v *gocui.View) error { downCommand := utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.Down, gui.DockerCommand.NewCommandObject(commands.CommandObject{}), ) downWithVolumesCommand := utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.DownWithVolumes, gui.DockerCommand.NewCommandObject(commands.CommandObject{}), ) options := []*commandOption{ { description: gui.Tr.Down, command: downCommand, onPress: func() error { return gui.WithWaitingStatus(gui.Tr.DowningStatus, func() error { if err := gui.OSCommand.RunCommand(downCommand); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, }, { description: gui.Tr.DownWithVolumes, command: downWithVolumesCommand, onPress: func() error { return gui.WithWaitingStatus(gui.Tr.DowningStatus, func() error { if err := gui.OSCommand.RunCommand(downWithVolumesCommand); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, }, } menuItems := lo.Map(options, func(option *commandOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: option.getDisplayStrings(), OnPress: option.onPress, } }) return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) handleServiceRestartMenu(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } rebuildCommand := utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.RebuildService, gui.DockerCommand.NewCommandObject(commands.CommandObject{Service: service}), ) recreateCommand := utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.RecreateService, gui.DockerCommand.NewCommandObject(commands.CommandObject{Service: service}), ) options := []*commandOption{ { description: gui.Tr.Restart, command: utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.RestartService, gui.DockerCommand.NewCommandObject(commands.CommandObject{Service: service}), ), onPress: func() error { return gui.WithWaitingStatus(gui.Tr.RestartingStatus, func() error { if err := service.Restart(); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, }, { description: gui.Tr.Recreate, command: utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.RecreateService, gui.DockerCommand.NewCommandObject(commands.CommandObject{Service: service}), ), onPress: func() error { return gui.WithWaitingStatus(gui.Tr.RestartingStatus, func() error { if err := gui.OSCommand.RunCommand(recreateCommand); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, }, { description: gui.Tr.Rebuild, command: utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.RebuildService, gui.DockerCommand.NewCommandObject(commands.CommandObject{Service: service}), ), onPress: func() error { return gui.runSubprocess(gui.OSCommand.RunCustomCommand(rebuildCommand)) }, }, } menuItems := lo.Map(options, func(option *commandOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: option.getDisplayStrings(), OnPress: option.onPress, } }) return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) handleServicesCustomCommand(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{ Service: service, Container: service.Container, }) var customCommands []config.CustomCommand customServiceCommands := gui.Config.UserConfig.CustomCommands.Services // we only include service commands if they have no serviceNames defined or if our service happens to be one of the serviceNames defined L: for _, cmd := range customServiceCommands { if len(cmd.ServiceNames) == 0 { customCommands = append(customCommands, cmd) continue L } for _, serviceName := range cmd.ServiceNames { if serviceName == service.Name { // appending these to the top given they're more likely to be selected customCommands = append([]config.CustomCommand{cmd}, customCommands...) continue L } } } if service.Container != nil { customCommands = append(customCommands, gui.Config.UserConfig.CustomCommands.Containers...) } return gui.createCustomCommandMenu(customCommands, commandObject) } func (gui *Gui) handleServicesBulkCommand(g *gocui.Gui, v *gocui.View) error { bulkCommands := gui.Config.UserConfig.BulkCommands.Services commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{}) return gui.createBulkCommandMenu(bulkCommands, commandObject) } func (gui *Gui) handleServicesExecShell(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } container := service.Container if container == nil { return gui.createErrorPanel(gui.Tr.NoContainers) } return gui.containerExecShell(container) } func (gui *Gui) handleServicesOpenInBrowserCommand(g *gocui.Gui, v *gocui.View) error { service, err := gui.Panels.Services.GetSelectedItem() if err != nil { return nil } container := service.Container if container == nil { return gui.createErrorPanel(gui.Tr.NoContainers) } return gui.openContainerInBrowser(container) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/main_panel.go
pkg/gui/main_panel.go
package gui import ( "math" "github.com/jesseduffield/gocui" ) func (gui *Gui) scrollUpMain() error { mainView := gui.Views.Main mainView.Autoscroll = false ox, oy := mainView.Origin() newOy := int(math.Max(0, float64(oy-gui.Config.UserConfig.Gui.ScrollHeight))) return mainView.SetOrigin(ox, newOy) } func (gui *Gui) scrollDownMain() error { mainView := gui.Views.Main mainView.Autoscroll = false ox, oy := mainView.Origin() reservedLines := 0 if !gui.Config.UserConfig.Gui.ScrollPastBottom { _, sizeY := mainView.Size() reservedLines = sizeY } totalLines := mainView.ViewLinesHeight() if oy+reservedLines >= totalLines { return nil } return mainView.SetOrigin(ox, oy+gui.Config.UserConfig.Gui.ScrollHeight) } func (gui *Gui) scrollLeftMain(g *gocui.Gui, v *gocui.View) error { mainView := gui.Views.Main ox, oy := mainView.Origin() newOx := int(math.Max(0, float64(ox-gui.Config.UserConfig.Gui.ScrollHeight))) return mainView.SetOrigin(newOx, oy) } func (gui *Gui) scrollRightMain(g *gocui.Gui, v *gocui.View) error { mainView := gui.Views.Main ox, oy := mainView.Origin() content := mainView.ViewBufferLines() var largestNumberOfCharacters int for _, txt := range content { if len(txt) > largestNumberOfCharacters { largestNumberOfCharacters = len(txt) } } sizeX, _ := mainView.Size() if ox+sizeX >= largestNumberOfCharacters { return nil } return mainView.SetOrigin(ox+gui.Config.UserConfig.Gui.ScrollHeight, oy) } func (gui *Gui) autoScrollMain(g *gocui.Gui, v *gocui.View) error { gui.Views.Main.Autoscroll = true return nil } func (gui *Gui) jumpToTopMain(g *gocui.Gui, v *gocui.View) error { gui.Views.Main.Autoscroll = false _ = gui.Views.Main.SetOrigin(0, 0) _ = gui.Views.Main.SetCursor(0, 0) return nil } func (gui *Gui) onMainTabClick(tabIndex int) error { gui.Log.Warn(tabIndex) currentSidePanel, ok := gui.currentSidePanel() if !ok { return nil } currentSidePanel.SetMainTabIndex(tabIndex) return currentSidePanel.HandleSelect() } func (gui *Gui) handleEnterMain(g *gocui.Gui, v *gocui.View) error { mainView := gui.Views.Main mainView.ParentView = v return gui.switchFocus(mainView) } func (gui *Gui) handleExitMain(g *gocui.Gui, v *gocui.View) error { v.ParentView = nil return gui.returnFocus() } func (gui *Gui) handleMainClick() error { if gui.popupPanelFocused() { return nil } currentView := gui.g.CurrentView() if currentView.Name() != "main" { gui.Views.Main.ParentView = currentView } return gui.switchFocus(gui.Views.Main) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/filtering.go
pkg/gui/filtering.go
package gui import ( "fmt" "github.com/jesseduffield/gocui" ) func (gui *Gui) handleOpenFilter() error { panel, ok := gui.currentListPanel() if !ok { return nil } if panel.IsFilterDisabled() { return nil } gui.State.Filter.active = true gui.State.Filter.panel = panel return gui.switchFocus(gui.Views.Filter) } func (gui *Gui) onNewFilterNeedle(value string) error { gui.State.Filter.needle = value gui.ResetOrigin(gui.State.Filter.panel.GetView()) return gui.State.Filter.panel.RerenderList() } func (gui *Gui) wrapEditor(f func(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool) func(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { return func(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) bool { matched := f(v, key, ch, mod) if matched { if err := gui.onNewFilterNeedle(v.TextArea.GetContent()); err != nil { gui.Log.Error(err) } } return matched } } func (gui *Gui) escapeFilterPrompt() error { if err := gui.clearFilter(); err != nil { return err } return gui.returnFocus() } func (gui *Gui) clearFilter() error { gui.State.Filter.needle = "" gui.State.Filter.active = false panel := gui.State.Filter.panel gui.State.Filter.panel = nil gui.Views.Filter.ClearTextArea() if panel == nil { return nil } gui.ResetOrigin(panel.GetView()) return panel.RerenderList() } // returns to the list view with the filter still applied func (gui *Gui) commitFilter() error { if gui.State.Filter.needle == "" { if err := gui.clearFilter(); err != nil { return err } } return gui.returnFocus() } func (gui *Gui) filterPrompt() string { return fmt.Sprintf("%s: ", gui.Tr.FilterPrompt) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/theme.go
pkg/gui/theme.go
package gui import ( "github.com/jesseduffield/gocui" ) // GetOptionsPanelTextColor gets the color of the options panel text func (gui *Gui) GetOptionsPanelTextColor() gocui.Attribute { return GetGocuiStyle(gui.Config.UserConfig.Gui.Theme.OptionsTextColor) } // SetColorScheme sets the color scheme for the app based on the user config func (gui *Gui) SetColorScheme() error { gui.g.FgColor = GetGocuiStyle(gui.Config.UserConfig.Gui.Theme.InactiveBorderColor) gui.g.SelFgColor = GetGocuiStyle(gui.Config.UserConfig.Gui.Theme.ActiveBorderColor) gui.g.FrameColor = gui.g.FgColor gui.g.SelFrameColor = gui.g.SelFgColor return nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/options_menu_panel.go
pkg/gui/options_menu_panel.go
package gui import ( "github.com/samber/lo" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/gui/types" ) func (gui *Gui) getBindings(v *gocui.View) []*Binding { var bindingsGlobal, bindingsPanel []*Binding bindings := gui.GetInitialKeybindings() for _, binding := range bindings { if binding.GetKey() != "" && binding.Description != "" { switch binding.ViewName { case "": bindingsGlobal = append(bindingsGlobal, binding) case v.Name(): bindingsPanel = append(bindingsPanel, binding) } } } // check if we have any keybindings from our parent view to add if v.ParentView != nil { L: for _, binding := range bindings { if binding.GetKey() != "" && binding.Description != "" { if binding.ViewName == v.ParentView.Name() { // if we haven't got a conflict we will display the binding for _, ownBinding := range bindingsPanel { if ownBinding.GetKey() == binding.GetKey() { continue L } } bindingsPanel = append(bindingsPanel, binding) } } } } // append dummy element to have a separator between // panel and global keybindings bindingsPanel = append(bindingsPanel, &Binding{}) return append(bindingsPanel, bindingsGlobal...) } func (gui *Gui) handleCreateOptionsMenu(g *gocui.Gui, v *gocui.View) error { if gui.isPopupPanel(v.Name()) { return nil } menuItems := lo.Map(gui.getBindings(v), func(binding *Binding, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{binding.GetKey(), binding.Description}, OnPress: func() error { if binding.Key == nil { return nil } return binding.Handler(g, v) }, } }) return gui.Menu(CreateMenuOptions{ Title: gui.Tr.MenuTitle, Items: menuItems, HideCancel: true, }) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/project_panel.go
pkg/gui/project_panel.go
package gui import ( "bytes" "context" "path" "strings" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/jesseduffield/yaml" ) // Although at the moment we'll only have one project, in future we could have // a list of projects in the project panel. func (gui *Gui) getProjectPanel() *panels.SideListPanel[*commands.Project] { return &panels.SideListPanel[*commands.Project]{ ContextState: &panels.ContextState[*commands.Project]{ GetMainTabs: func() []panels.MainTab[*commands.Project] { if gui.DockerCommand.InDockerComposeProject { return []panels.MainTab[*commands.Project]{ { Key: "logs", Title: gui.Tr.LogsTitle, Render: gui.renderAllLogs, }, { Key: "config", Title: gui.Tr.DockerComposeConfigTitle, Render: gui.renderDockerComposeConfig, }, { Key: "credits", Title: gui.Tr.CreditsTitle, Render: gui.renderCredits, }, } } return []panels.MainTab[*commands.Project]{ { Key: "credits", Title: gui.Tr.CreditsTitle, Render: gui.renderCredits, }, } }, GetItemContextCacheKey: func(project *commands.Project) string { return "projects-" + project.Name }, }, ListPanel: panels.ListPanel[*commands.Project]{ List: panels.NewFilteredList[*commands.Project](), View: gui.Views.Project, }, NoItemsMessage: "", Gui: gui.intoInterface(), Sort: func(a *commands.Project, b *commands.Project) bool { return false }, GetTableCells: presentation.GetProjectDisplayStrings, // It doesn't make sense to filter a list of only one item. DisableFilter: true, } } func (gui *Gui) refreshProject() error { gui.Panels.Projects.SetItems([]*commands.Project{{Name: gui.getProjectName()}}) return gui.Panels.Projects.RerenderList() } func (gui *Gui) getProjectName() string { projectName := path.Base(gui.Config.ProjectDir) if gui.DockerCommand.InDockerComposeProject { for _, service := range gui.Panels.Services.List.GetAllItems() { container := service.Container if container != nil && container.DetailsLoaded() { return container.Details.Config.Labels["com.docker.compose.project"] } } } return projectName } func (gui *Gui) renderCredits(_project *commands.Project) tasks.TaskFunc { return gui.NewSimpleRenderStringTask(func() string { return gui.creditsStr() }) } func (gui *Gui) creditsStr() string { var configBuf bytes.Buffer _ = yaml.NewEncoder(&configBuf, yaml.IncludeOmitted).Encode(gui.Config.UserConfig) return strings.Join( []string{ lazydockerTitle(), "Copyright (c) 2019 Jesse Duffield", "Keybindings: https://github.com/jesseduffield/lazydocker/blob/master/docs/keybindings", "Config Options: https://github.com/jesseduffield/lazydocker/blob/master/docs/Config.md", "Raise an Issue: https://github.com/jesseduffield/lazydocker/issues", utils.ColoredString("Buy Jesse a coffee: https://github.com/sponsors/jesseduffield", color.FgMagenta), // caffeine ain't free "Here's your lazydocker config when merged in with the defaults (you can open your config by pressing 'o'):", utils.ColoredYamlString(configBuf.String()), }, "\n\n") } func (gui *Gui) renderAllLogs(_project *commands.Project) tasks.TaskFunc { return gui.NewTask(TaskOpts{ Autoscroll: true, Wrap: gui.Config.UserConfig.Gui.WrapMainPanel, Func: func(ctx context.Context) { gui.clearMainView() cmd := gui.OSCommand.RunCustomCommand( utils.ApplyTemplate( gui.Config.UserConfig.CommandTemplates.AllLogs, gui.DockerCommand.NewCommandObject(commands.CommandObject{}), ), ) cmd.Stdout = gui.Views.Main cmd.Stderr = gui.Views.Main gui.OSCommand.PrepareForChildren(cmd) _ = cmd.Start() go func() { <-ctx.Done() if err := gui.OSCommand.Kill(cmd); err != nil { gui.Log.Error(err) } }() _ = cmd.Wait() }, }) } func (gui *Gui) renderDockerComposeConfig(_project *commands.Project) tasks.TaskFunc { return gui.NewSimpleRenderStringTask(func() string { return utils.ColoredYamlString(gui.DockerCommand.DockerComposeConfig()) }) } func (gui *Gui) handleOpenConfig(g *gocui.Gui, v *gocui.View) error { return gui.openFile(gui.Config.ConfigFilename()) } func (gui *Gui) handleEditConfig(g *gocui.Gui, v *gocui.View) error { return gui.editFile(gui.Config.ConfigFilename()) } func lazydockerTitle() string { return ` _ _ _ | | | | | | | | __ _ _____ _ __| | ___ ___| | _____ _ __ | |/ _` + "`" + ` |_ / | | |/ _` + "`" + ` |/ _ \ / __| |/ / _ \ '__| | | (_| |/ /| |_| | (_| | (_) | (__| < __/ | |_|\__,_/___|\__, |\__,_|\___/ \___|_|\_\___|_| __/ | |___/ ` } // handleViewAllLogs switches to a subprocess viewing all the logs from docker-compose func (gui *Gui) handleViewAllLogs(g *gocui.Gui, v *gocui.View) error { c, err := gui.DockerCommand.ViewAllLogs() if err != nil { return gui.createErrorPanel(err.Error()) } return gui.runSubprocess(c) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/gocui.go
pkg/gui/gocui.go
package gui import ( "github.com/gookit/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/utils" ) var gocuiColorMap = map[string]gocui.Attribute{ "default": gocui.ColorDefault, "black": gocui.ColorBlack, "red": gocui.ColorRed, "green": gocui.ColorGreen, "yellow": gocui.ColorYellow, "blue": gocui.ColorBlue, "magenta": gocui.ColorMagenta, "cyan": gocui.ColorCyan, "white": gocui.ColorWhite, "bold": gocui.AttrBold, "reverse": gocui.AttrReverse, "underline": gocui.AttrUnderline, } // GetAttribute gets the gocui color attribute from the string func GetGocuiAttribute(key string) gocui.Attribute { if utils.IsValidHexValue(key) { values := color.HEX(key).Values() return gocui.NewRGBColor(int32(values[0]), int32(values[1]), int32(values[2])) } value, present := gocuiColorMap[key] if present { return value } return gocui.ColorDefault } // GetGocuiStyle bitwise OR's a list of attributes obtained via the given keys func GetGocuiStyle(keys []string) gocui.Attribute { var attribute gocui.Attribute for _, key := range keys { attribute |= GetGocuiAttribute(key) } return attribute }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/gui.go
pkg/gui/gui.go
package gui import ( "context" "os" "strings" "time" "github.com/docker/docker/api/types/events" "github.com/go-errors/errors" throttle "github.com/boz/go-throttle" "github.com/jesseduffield/gocui" lcUtils "github.com/jesseduffield/lazycore/pkg/utils" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/i18n" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/sasha-s/go-deadlock" "github.com/sirupsen/logrus" ) // Gui wraps the gocui Gui object which handles rendering and events type Gui struct { g *gocui.Gui Log *logrus.Entry DockerCommand *commands.DockerCommand OSCommand *commands.OSCommand State guiState Config *config.AppConfig Tr *i18n.TranslationSet statusManager *statusManager taskManager *tasks.TaskManager ErrorChan chan error Views Views // if we've suspended the gui (e.g. because we've switched to a subprocess) // we typically want to pause some things that are running like background // file refreshes PauseBackgroundThreads bool Mutexes Panels Panels } type Panels struct { Projects *panels.SideListPanel[*commands.Project] Services *panels.SideListPanel[*commands.Service] Containers *panels.SideListPanel[*commands.Container] Images *panels.SideListPanel[*commands.Image] Volumes *panels.SideListPanel[*commands.Volume] Networks *panels.SideListPanel[*commands.Network] Menu *panels.SideListPanel[*types.MenuItem] } type Mutexes struct { SubprocessMutex deadlock.Mutex ViewStackMutex deadlock.Mutex } type mainPanelState struct { // ObjectKey tells us what context we are in. For example, if we are looking at the logs of a particular service in the services panel this key might be 'services-<service id>-logs'. The key is made so that if something changes which might require us to re-run the logs command or run a different command, the key will be different, and we'll then know to do whatever is required. Object key probably isn't the best name for this but Context is already used to refer to tabs. Maybe I should just call them tabs. ObjectKey string } type panelStates struct { Main *mainPanelState } type guiState struct { // the names of views in the current focus stack (last item is the current view) ViewStack []string Platform commands.Platform Panels *panelStates SubProcessOutput string Stats map[string]commands.ContainerStats // if true, we show containers with an 'exited' status in the containers panel ShowExitedContainers bool ScreenMode WindowMaximisation // Maintains the state of manual filtering i.e. typing in a substring // to filter on in the current panel. Filter filterState } type filterState struct { // If true then we're either currently inside the filter view // or we've committed the filter and we're back in the list view active bool // The panel that we're filtering. panel panels.ISideListPanel // The string that we're filtering on needle string } // screen sizing determines how much space your selected window takes up (window // as in panel, not your terminal's window). Sometimes you want a bit more space // to see the contents of a panel, and this keeps track of how much maximisation // you've set type WindowMaximisation int const ( SCREEN_NORMAL WindowMaximisation = iota SCREEN_HALF SCREEN_FULL ) func getScreenMode(config *config.AppConfig) WindowMaximisation { switch config.UserConfig.Gui.ScreenMode { case "normal": return SCREEN_NORMAL case "half": return SCREEN_HALF case "fullscreen": return SCREEN_FULL default: return SCREEN_NORMAL } } // NewGui builds a new gui handler func NewGui(log *logrus.Entry, dockerCommand *commands.DockerCommand, oSCommand *commands.OSCommand, tr *i18n.TranslationSet, config *config.AppConfig, errorChan chan error) (*Gui, error) { initialState := guiState{ Platform: *oSCommand.Platform, Panels: &panelStates{ Main: &mainPanelState{ ObjectKey: "", }, }, ViewStack: []string{}, ShowExitedContainers: true, ScreenMode: getScreenMode(config), } gui := &Gui{ Log: log, DockerCommand: dockerCommand, OSCommand: oSCommand, State: initialState, Config: config, Tr: tr, statusManager: &statusManager{}, taskManager: tasks.NewTaskManager(log, tr), ErrorChan: errorChan, } deadlock.Opts.Disable = !gui.Config.Debug deadlock.Opts.DeadlockTimeout = 10 * time.Second return gui, nil } func (gui *Gui) renderGlobalOptions() error { return gui.renderOptionsMap(map[string]string{ "PgUp/PgDn": gui.Tr.Scroll, "← → ↑ ↓": gui.Tr.Navigate, "q": gui.Tr.Quit, "b": gui.Tr.ViewBulkCommands, "x": gui.Tr.Menu, }) } func (gui *Gui) goEvery(interval time.Duration, function func() error) { _ = function() // time.Tick doesn't run immediately so we'll do that here // TODO: maybe change go func() { ticker := time.NewTicker(interval) defer ticker.Stop() for range ticker.C { if !gui.PauseBackgroundThreads { _ = function() } } }() } // Run setup the gui with keybindings and start the mainloop func (gui *Gui) Run() error { // closing our task manager which in turn closes the current task if there is any, so we aren't leaving processes lying around after closing lazydocker defer gui.taskManager.Close() g, err := gocui.NewGui(gocui.NewGuiOpts{ OutputMode: gocui.OutputTrue, RuneReplacements: map[rune]string{}, }) if err != nil { return err } defer g.Close() // forgive the double-negative, this is because of my yaml `omitempty` woes if !gui.Config.UserConfig.Gui.IgnoreMouseEvents { g.Mouse = true } gui.g = g // TODO: always use gui.g rather than passing g around everywhere // if the deadlock package wants to report a deadlock, we first need to // close the gui so that we can actually read what it prints. deadlock.Opts.LogBuf = lcUtils.NewOnceWriter(os.Stderr, func() { gui.g.Close() }) if err := gui.SetColorScheme(); err != nil { return err } throttledRefresh := throttle.ThrottleFunc(time.Millisecond*50, true, gui.refresh) defer throttledRefresh.Stop() go func() { for err := range gui.ErrorChan { if err == nil { continue } if strings.Contains(err.Error(), "No such container") { // this happens all the time when e.g. restarting containers so we won't worry about it gui.Log.Warn(err) continue } _ = gui.createErrorPanel(err.Error()) } }() g.SetManager(gocui.ManagerFunc(gui.layout), gocui.ManagerFunc(gui.getFocusLayout())) if err := gui.createAllViews(); err != nil { return err } if err := gui.setInitialViewContent(); err != nil { return err } // TODO: see if we can avoid the circular dependency gui.setPanels() if err = gui.keybindings(g); err != nil { return err } if gui.g.CurrentView() == nil { viewName := gui.initiallyFocusedViewName() view, err := gui.g.View(viewName) if err != nil { return err } if err := gui.switchFocus(view); err != nil { return err } } ctx, finish := context.WithCancel(context.Background()) defer finish() go gui.listenForEvents(ctx, throttledRefresh.Trigger) go gui.monitorContainerStats(ctx) go func() { throttledRefresh.Trigger() gui.goEvery(time.Millisecond*30, gui.reRenderMain) gui.goEvery(time.Millisecond*1000, gui.updateContainerDetails) gui.goEvery(time.Millisecond*1000, gui.checkForContextChange) // we need to regularly re-render these because their stats will be changed in the background gui.goEvery(time.Millisecond*1000, gui.renderContainersAndServices) }() err = g.MainLoop() if err == gocui.ErrQuit { return nil } return err } func (gui *Gui) setPanels() { gui.Panels = Panels{ Projects: gui.getProjectPanel(), Services: gui.getServicesPanel(), Containers: gui.getContainersPanel(), Images: gui.getImagesPanel(), Volumes: gui.getVolumesPanel(), Networks: gui.getNetworksPanel(), Menu: gui.getMenuPanel(), } } func (gui *Gui) updateContainerDetails() error { return gui.DockerCommand.RefreshContainerDetails(gui.Panels.Containers.List.GetAllItems()) } func (gui *Gui) refresh() { go func() { if err := gui.refreshProject(); err != nil { gui.Log.Error(err) } }() go func() { if err := gui.refreshContainersAndServices(); err != nil { gui.Log.Error(err) } }() go func() { if err := gui.reloadVolumes(); err != nil { gui.Log.Error(err) } }() go func() { if err := gui.reloadNetworks(); err != nil { gui.Log.Error(err) } }() go func() { if err := gui.reloadImages(); err != nil { gui.Log.Error(err) } }() } func (gui *Gui) listenForEvents(ctx context.Context, refresh func()) { errorCount := 0 onError := func(err error) { if err != nil { gui.ErrorChan <- errors.Errorf("Docker event stream returned error: %s\nRetry count: %d", err.Error(), errorCount) } errorCount++ time.Sleep(time.Second * 2) } outer: for { messageChan, errChan := gui.DockerCommand.Client.Events(context.Background(), events.ListOptions{}) if errorCount > 0 { select { case <-ctx.Done(): return case err := <-errChan: onError(err) continue outer default: // If we're here then we lost connection to docker and we just got it back. // The reason we do this refresh explicitly is because successfully // reconnecting with docker does not mean it's going to send us a new // event any time soon. // Assuming the confirmation prompt currently holds the given error _ = gui.closeConfirmationPrompt() refresh() errorCount = 0 } } for { select { case <-ctx.Done(): return case message := <-messageChan: // We could be more granular about what events should trigger which refreshes. // At the moment it's pretty efficient though, and it might not be worth // the maintenance burden of mapping specific events to specific refreshes refresh() gui.Log.Infof("received event of type: %s", message.Type) case err := <-errChan: onError(err) continue outer } } } } // checkForContextChange runs the currently focused panel's 'select' function, simulating the current item having just been selected. This will then trigger a check to see if anything's changed (e.g. a service has a new container) and if so, the appropriate code will run. For example, if you're reading logs from a service and all of a sudden its container changes, this will trigger the 'select' function, which will work out that the context is not different because of the new container, and then it will re-attempt to get the logs, this time for the correct container. This 'context' is stored in the main panel's ObjectKey. I'm using the term 'context' here more broadly than just the different tabs you can view in a panel. func (gui *Gui) checkForContextChange() error { return gui.newLineFocused(gui.g.CurrentView()) } func (gui *Gui) reRenderMain() error { mainView := gui.Views.Main if mainView == nil { return nil } if mainView.IsTainted() { gui.g.Update(func(g *gocui.Gui) error { return nil }) } return nil } func (gui *Gui) quit(g *gocui.Gui, v *gocui.View) error { if gui.Config.UserConfig.ConfirmOnQuit { return gui.createConfirmationPanel("", gui.Tr.ConfirmQuit, func(g *gocui.Gui, v *gocui.View) error { return gocui.ErrQuit }, nil) } return gocui.ErrQuit } // this handler is executed when we press escape when there is only one view // on the stack. func (gui *Gui) escape() error { if gui.State.Filter.active { return gui.clearFilter() } return nil } func (gui *Gui) handleDonate(g *gocui.Gui, v *gocui.View) error { if !gui.g.Mouse { return nil } cx, _ := v.Cursor() if cx > len(gui.Tr.Donate) { return nil } return gui.OSCommand.OpenLink("https://github.com/sponsors/jesseduffield") } func (gui *Gui) editFile(filename string) error { cmd, err := gui.OSCommand.EditFile(filename) if err != nil { return gui.createErrorPanel(err.Error()) } return gui.runSubprocess(cmd) } func (gui *Gui) openFile(filename string) error { if err := gui.OSCommand.OpenFile(filename); err != nil { return gui.createErrorPanel(err.Error()) } return nil } func (gui *Gui) handleCustomCommand(g *gocui.Gui, v *gocui.View) error { return gui.createPromptPanel(gui.Tr.CustomCommandTitle, func(g *gocui.Gui, v *gocui.View) error { command := gui.trimmedContent(v) return gui.runSubprocess(gui.OSCommand.RunCustomCommand(command)) }) } func (gui *Gui) ShouldRefresh(key string) bool { if gui.State.Panels.Main.ObjectKey == key { return false } gui.State.Panels.Main.ObjectKey = key return true } func (gui *Gui) initiallyFocusedViewName() string { if gui.DockerCommand.InDockerComposeProject { return "services" } return "containers" } func (gui *Gui) IgnoreStrings() []string { return gui.Config.UserConfig.Ignore } func (gui *Gui) Update(f func() error) { gui.g.Update(func(*gocui.Gui) error { return f() }) } func (gui *Gui) monitorContainerStats(ctx context.Context) { // periodically loop through running containers and see if we need to create a monitor goroutine for any // every second we check if we need to spawn a new goroutine ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: for _, container := range gui.Panels.Containers.List.GetAllItems() { if !container.MonitoringStats { go gui.DockerCommand.CreateClientStatMonitor(container) } } } } } // this is used by our cheatsheet code to generate keybindings. We need some views // and panels to exist for us to know what keybindings there are, so we invoke // gocui in headless mode and create them. func (gui *Gui) SetupFakeGui() { g, err := gocui.NewGui(gocui.NewGuiOpts{ OutputMode: gocui.OutputTrue, RuneReplacements: map[rune]string{}, Headless: true, }) if err != nil { panic(err) } gui.g = g defer g.Close() if err := gui.createAllViews(); err != nil { panic(err) } gui.setPanels() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/subprocess.go
pkg/gui/subprocess.go
package gui import ( "fmt" "io" "os" "os/exec" "os/signal" "strings" "github.com/fatih/color" "github.com/jesseduffield/lazydocker/pkg/utils" ) func (gui *Gui) runSubprocess(cmd *exec.Cmd) error { return gui.runSubprocessWithMessage(cmd, "") } func (gui *Gui) runSubprocessWithMessage(cmd *exec.Cmd, msg string) error { gui.Mutexes.SubprocessMutex.Lock() defer gui.Mutexes.SubprocessMutex.Unlock() if err := gui.g.Suspend(); err != nil { return gui.createErrorPanel(err.Error()) } gui.PauseBackgroundThreads = true gui.runCommand(cmd, msg) if err := gui.g.Resume(); err != nil { return gui.createErrorPanel(err.Error()) } gui.PauseBackgroundThreads = false return nil } func (gui *Gui) runCommand(cmd *exec.Cmd, msg string) { cmd.Stdout = os.Stdout cmd.Stderr = os.Stdout cmd.Stdin = os.Stdin stop := make(chan os.Signal, 1) defer signal.Stop(stop) go func() { signal.Notify(stop, os.Interrupt) <-stop if err := gui.OSCommand.Kill(cmd); err != nil { gui.Log.Error(err) } }() fmt.Fprintf(os.Stdout, "\n%s\n\n", utils.ColoredString("+ "+strings.Join(cmd.Args, " "), color.FgBlue)) if msg != "" { fmt.Fprintf(os.Stdout, "\n%s\n\n", utils.ColoredString(msg, color.FgGreen)) } if err := cmd.Run(); err != nil { // not handling the error explicitly because usually we're going to see it // in the output anyway gui.Log.Error(err) } cmd.Stdin = nil cmd.Stdout = io.Discard cmd.Stderr = io.Discard gui.promptToReturn() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/volumes_panel.go
pkg/gui/volumes_panel.go
package gui import ( "fmt" "github.com/fatih/color" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/gui/panels" "github.com/jesseduffield/lazydocker/pkg/gui/presentation" "github.com/jesseduffield/lazydocker/pkg/gui/types" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func (gui *Gui) getVolumesPanel() *panels.SideListPanel[*commands.Volume] { return &panels.SideListPanel[*commands.Volume]{ ContextState: &panels.ContextState[*commands.Volume]{ GetMainTabs: func() []panels.MainTab[*commands.Volume] { return []panels.MainTab[*commands.Volume]{ { Key: "config", Title: gui.Tr.ConfigTitle, Render: gui.renderVolumeConfig, }, } }, GetItemContextCacheKey: func(volume *commands.Volume) string { return "volumes-" + volume.Name }, }, ListPanel: panels.ListPanel[*commands.Volume]{ List: panels.NewFilteredList[*commands.Volume](), View: gui.Views.Volumes, }, NoItemsMessage: gui.Tr.NoVolumes, Gui: gui.intoInterface(), // we're sorting these volumes based on whether they have labels defined, // because those are the ones you typically care about. // Within that, we also sort them alphabetically Sort: func(a *commands.Volume, b *commands.Volume) bool { if len(a.Volume.Labels) == 0 && len(b.Volume.Labels) > 0 { return false } if len(a.Volume.Labels) > 0 && len(b.Volume.Labels) == 0 { return true } return a.Name < b.Name }, GetTableCells: presentation.GetVolumeDisplayStrings, } } func (gui *Gui) renderVolumeConfig(volume *commands.Volume) tasks.TaskFunc { return gui.NewSimpleRenderStringTask(func() string { return gui.volumeConfigStr(volume) }) } func (gui *Gui) volumeConfigStr(volume *commands.Volume) string { padding := 15 output := "" output += utils.WithPadding("Name: ", padding) + volume.Name + "\n" output += utils.WithPadding("Driver: ", padding) + volume.Volume.Driver + "\n" output += utils.WithPadding("Scope: ", padding) + volume.Volume.Scope + "\n" output += utils.WithPadding("Mountpoint: ", padding) + volume.Volume.Mountpoint + "\n" output += utils.WithPadding("Labels: ", padding) + utils.FormatMap(padding, volume.Volume.Labels) + "\n" output += utils.WithPadding("Options: ", padding) + utils.FormatMap(padding, volume.Volume.Options) + "\n" output += utils.WithPadding("Status: ", padding) if volume.Volume.Status != nil { output += "\n" for k, v := range volume.Volume.Status { output += utils.FormatMapItem(padding, k, v) } } else { output += "n/a" } if volume.Volume.UsageData != nil { output += utils.WithPadding("RefCount: ", padding) + fmt.Sprintf("%d", volume.Volume.UsageData.RefCount) + "\n" output += utils.WithPadding("Size: ", padding) + utils.FormatBinaryBytes(int(volume.Volume.UsageData.Size)) + "\n" } return output } func (gui *Gui) reloadVolumes() error { if err := gui.refreshStateVolumes(); err != nil { return err } return gui.Panels.Volumes.RerenderList() } func (gui *Gui) refreshStateVolumes() error { volumes, err := gui.DockerCommand.RefreshVolumes() if err != nil { return err } gui.Panels.Volumes.SetItems(volumes) return nil } func (gui *Gui) handleVolumesRemoveMenu(g *gocui.Gui, v *gocui.View) error { volume, err := gui.Panels.Volumes.GetSelectedItem() if err != nil { return nil } type removeVolumeOption struct { description string command string force bool } options := []*removeVolumeOption{ { description: gui.Tr.Remove, command: utils.WithShortSha("docker volume rm " + volume.Name), force: false, }, { description: gui.Tr.ForceRemove, command: utils.WithShortSha("docker volume rm --force " + volume.Name), force: true, }, } menuItems := lo.Map(options, func(option *removeVolumeOption, _ int) *types.MenuItem { return &types.MenuItem{ LabelColumns: []string{option.description, color.New(color.FgRed).Sprint(option.command)}, OnPress: func() error { return gui.WithWaitingStatus(gui.Tr.RemovingStatus, func() error { if err := volume.Remove(option.force); err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, } }) return gui.Menu(CreateMenuOptions{ Title: "", Items: menuItems, }) } func (gui *Gui) handlePruneVolumes() error { return gui.createConfirmationPanel(gui.Tr.Confirm, gui.Tr.ConfirmPruneVolumes, func(g *gocui.Gui, v *gocui.View) error { return gui.WithWaitingStatus(gui.Tr.PruningStatus, func() error { err := gui.DockerCommand.PruneVolumes() if err != nil { return gui.createErrorPanel(err.Error()) } return nil }) }, nil) } func (gui *Gui) handleVolumesCustomCommand(g *gocui.Gui, v *gocui.View) error { volume, err := gui.Panels.Volumes.GetSelectedItem() if err != nil { return nil } commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{ Volume: volume, }) customCommands := gui.Config.UserConfig.CustomCommands.Volumes return gui.createCustomCommandMenu(customCommands, commandObject) } func (gui *Gui) handleVolumesBulkCommand(g *gocui.Gui, v *gocui.View) error { baseBulkCommands := []config.CustomCommand{ { Name: gui.Tr.PruneVolumes, InternalFunction: gui.handlePruneVolumes, }, } bulkCommands := append(baseBulkCommands, gui.Config.UserConfig.BulkCommands.Volumes...) commandObject := gui.DockerCommand.NewCommandObject(commands.CommandObject{}) return gui.createBulkCommandMenu(bulkCommands, commandObject) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/networks.go
pkg/gui/presentation/networks.go
package presentation import "github.com/jesseduffield/lazydocker/pkg/commands" func GetNetworkDisplayStrings(network *commands.Network) []string { return []string{network.Network.Driver, network.Name} }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/projects.go
pkg/gui/presentation/projects.go
package presentation import "github.com/jesseduffield/lazydocker/pkg/commands" func GetProjectDisplayStrings(project *commands.Project) []string { return []string{project.Name} }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/images.go
pkg/gui/presentation/images.go
package presentation import ( "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/utils" ) func GetImageDisplayStrings(image *commands.Image) []string { return []string{ image.Name, image.Tag, utils.FormatDecimalBytes(int(image.Image.Size)), } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/container_stats.go
pkg/gui/presentation/container_stats.go
package presentation import ( "fmt" "math" "reflect" "strconv" "strings" "time" "github.com/fatih/color" "github.com/jesseduffield/asciigraph" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/mcuadros/go-lookup" "github.com/samber/lo" ) func RenderStats(userConfig *config.UserConfig, container *commands.Container, viewWidth int) (string, error) { stats, ok := container.GetLastStats() if !ok { return "", nil } graphSpecs := userConfig.Stats.Graphs graphs := make([]string, len(graphSpecs)) for i, spec := range graphSpecs { graph, err := plotGraph(container, spec, viewWidth-10) if err != nil { return "", err } graphs[i] = utils.ColoredString(graph, utils.GetColorAttribute(spec.Color)) } pidsCount := fmt.Sprintf("PIDs: %d", stats.ClientStats.PidsStats.Current) dataReceived := fmt.Sprintf("Traffic received: %s", utils.FormatDecimalBytes(stats.ClientStats.Networks.Eth0.RxBytes)) dataSent := fmt.Sprintf("Traffic sent: %s", utils.FormatDecimalBytes(stats.ClientStats.Networks.Eth0.TxBytes)) originalStats, err := utils.MarshalIntoYaml(stats) if err != nil { return "", err } contents := fmt.Sprintf("\n\n%s\n\n%s\n\n%s\n%s\n\n%s", utils.ColoredString(strings.Join(graphs, "\n\n"), color.FgGreen), pidsCount, dataReceived, dataSent, utils.ColoredYamlString(string(originalStats)), ) return contents, nil } // plotGraph returns the plotted graph based on the graph spec and the stat history func plotGraph(container *commands.Container, spec config.GraphConfig, width int) (string, error) { container.StatsMutex.Lock() defer container.StatsMutex.Unlock() data := make([]float64, len(container.StatHistory)) for i, stats := range container.StatHistory { value, err := lookup.LookupString(stats, spec.StatPath) if err != nil { return "Could not find key: " + spec.StatPath, nil } floatValue, err := getFloat(value.Interface()) if err != nil { return "", err } data[i] = floatValue } max := spec.Max if spec.MaxType == "" { max = lo.Max(data) } min := spec.Min if spec.MinType == "" { min = lo.Min(data) } height := 10 if spec.Height > 0 { height = spec.Height } caption := fmt.Sprintf( "%s: %0.2f (%v)", spec.Caption, data[len(data)-1], time.Since(container.StatHistory[0].RecordedAt).Round(time.Second), ) return asciigraph.Plot( data, asciigraph.Height(height), asciigraph.Width(width), asciigraph.Min(min), asciigraph.Max(max), asciigraph.Caption(caption), ), nil } // from Dave C's answer at https://stackoverflow.com/questions/20767724/converting-unknown-interface-to-float64-in-golang func getFloat(unk interface{}) (float64, error) { floatType := reflect.TypeOf(float64(0)) stringType := reflect.TypeOf("") switch i := unk.(type) { case float64: return i, nil case float32: return float64(i), nil case int64: return float64(i), nil case int32: return float64(i), nil case int: return float64(i), nil case uint64: return float64(i), nil case uint32: return float64(i), nil case uint: return float64(i), nil case string: return strconv.ParseFloat(i, 64) default: v := reflect.ValueOf(unk) v = reflect.Indirect(v) if v.Type().ConvertibleTo(floatType) { fv := v.Convert(floatType) return fv.Float(), nil } else if v.Type().ConvertibleTo(stringType) { sv := v.Convert(stringType) s := sv.String() return strconv.ParseFloat(s, 64) } else { return math.NaN(), fmt.Errorf("Can't convert %v to float64", v.Type()) } } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/containers.go
pkg/gui/presentation/containers.go
package presentation import ( "fmt" "sort" "strconv" "strings" "github.com/docker/docker/api/types/container" "github.com/fatih/color" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) func GetContainerDisplayStrings(guiConfig *config.GuiConfig, container *commands.Container) []string { return []string{ getContainerDisplayStatus(guiConfig, container), getContainerDisplaySubstatus(guiConfig, container), container.Name, getDisplayCPUPerc(container), utils.ColoredString(displayPorts(container), color.FgYellow), utils.ColoredString(displayContainerImage(container), color.FgMagenta), } } func displayContainerImage(container *commands.Container) string { return strings.TrimPrefix(container.Container.Image, "sha256:") } func displayPorts(c *commands.Container) string { portStrings := lo.Map(c.Container.Ports, func(port container.Port, _ int) string { if port.PublicPort == 0 { return fmt.Sprintf("%d/%s", port.PrivatePort, port.Type) } // docker ps will show '0.0.0.0:80->80/tcp' but we'll show // '80->80/tcp' instead to save space (unless the IP is something other than // 0.0.0.0) ipString := "" if port.IP != "0.0.0.0" { ipString = port.IP + ":" } return fmt.Sprintf("%s%d->%d/%s", ipString, port.PublicPort, port.PrivatePort, port.Type) }) // sorting because the order of the ports is not deterministic // and we don't want to have them constantly swapping sort.Strings(portStrings) return strings.Join(portStrings, ", ") } // getContainerDisplayStatus returns the colored status of the container func getContainerDisplayStatus(guiConfig *config.GuiConfig, c *commands.Container) string { shortStatusMap := map[string]string{ "paused": "P", "exited": "X", "created": "C", "removing": "RM", "restarting": "RS", "running": "R", "dead": "D", } iconStatusMap := map[string]rune{ "paused": '◫', "exited": '⨯', "created": '+', "removing": '−', "restarting": '⟳', "running": '▶', "dead": '!', } var containerState string switch guiConfig.ContainerStatusHealthStyle { case "short": containerState = shortStatusMap[c.Container.State] case "icon": containerState = string(iconStatusMap[c.Container.State]) case "long": fallthrough default: containerState = c.Container.State } return utils.ColoredString(containerState, getContainerColor(c)) } // GetDisplayStatus returns the exit code if the container has exited, and the health status if the container is running (and has a health check) func getContainerDisplaySubstatus(guiConfig *config.GuiConfig, c *commands.Container) string { if !c.DetailsLoaded() { return "" } switch c.Container.State { case "exited": return utils.ColoredString( fmt.Sprintf("(%s)", strconv.Itoa(c.Details.State.ExitCode)), getContainerColor(c), ) case "running": return getHealthStatus(guiConfig, c) default: return "" } } func getHealthStatus(guiConfig *config.GuiConfig, c *commands.Container) string { if !c.DetailsLoaded() { return "" } healthStatusColorMap := map[string]color.Attribute{ "healthy": color.FgGreen, "unhealthy": color.FgRed, "starting": color.FgYellow, } if c.Details.State.Health == nil { return "" } shortHealthStatusMap := map[string]string{ "healthy": "H", "unhealthy": "U", "starting": "S", } iconHealthStatusMap := map[string]rune{ "healthy": '✔', "unhealthy": '?', "starting": '…', } var healthStatus string switch guiConfig.ContainerStatusHealthStyle { case "short": healthStatus = shortHealthStatusMap[c.Details.State.Health.Status] case "icon": healthStatus = string(iconHealthStatusMap[c.Details.State.Health.Status]) case "long": fallthrough default: healthStatus = c.Details.State.Health.Status } if healthStatusColor, ok := healthStatusColorMap[c.Details.State.Health.Status]; ok { return utils.ColoredString(fmt.Sprintf("(%s)", healthStatus), healthStatusColor) } return "" } // getDisplayCPUPerc colors the cpu percentage based on how extreme it is func getDisplayCPUPerc(c *commands.Container) string { stats, ok := c.GetLastStats() if !ok { return "" } percentage := stats.DerivedStats.CPUPercentage formattedPercentage := fmt.Sprintf("%.2f%%", stats.DerivedStats.CPUPercentage) var clr color.Attribute if percentage > 90 { clr = color.FgRed } else if percentage > 50 { clr = color.FgYellow } else { clr = color.FgWhite } return utils.ColoredString(formattedPercentage, clr) } // getContainerColor Container color func getContainerColor(c *commands.Container) color.Attribute { switch c.Container.State { case "exited": // This means the colour may be briefly yellow and then switch to red upon starting // Not sure what a better alternative is. if !c.DetailsLoaded() || c.Details.State.ExitCode == 0 { return color.FgYellow } return color.FgRed case "created": return color.FgCyan case "running": return color.FgGreen case "paused": return color.FgYellow case "dead": return color.FgRed case "restarting": return color.FgBlue case "removing": return color.FgMagenta default: return color.FgWhite } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/services.go
pkg/gui/presentation/services.go
package presentation import ( "github.com/fatih/color" "github.com/jesseduffield/lazydocker/pkg/commands" "github.com/jesseduffield/lazydocker/pkg/config" "github.com/jesseduffield/lazydocker/pkg/utils" ) func GetServiceDisplayStrings(guiConfig *config.GuiConfig, service *commands.Service) []string { if service.Container == nil { var containerState string switch guiConfig.ContainerStatusHealthStyle { case "short": containerState = "n" case "icon": containerState = "." case "long": fallthrough default: containerState = "none" } return []string{ utils.ColoredString(containerState, color.FgBlue), "", service.Name, "", "", "", } } container := service.Container return []string{ getContainerDisplayStatus(guiConfig, container), getContainerDisplaySubstatus(guiConfig, container), service.Name, getDisplayCPUPerc(container), utils.ColoredString(displayPorts(container), color.FgYellow), utils.ColoredString(displayContainerImage(container), color.FgMagenta), } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/volumes.go
pkg/gui/presentation/volumes.go
package presentation import "github.com/jesseduffield/lazydocker/pkg/commands" func GetVolumeDisplayStrings(volume *commands.Volume) []string { return []string{volume.Volume.Driver, volume.Name} }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/presentation/menu_items.go
pkg/gui/presentation/menu_items.go
package presentation import "github.com/jesseduffield/lazydocker/pkg/gui/types" func GetMenuItemDisplayStrings(menuItem *types.MenuItem) []string { return menuItem.LabelColumns }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/types/types.go
pkg/gui/types/types.go
package types type MenuItem struct { Label string // alternative to Label. Allows specifying columns which will be auto-aligned LabelColumns []string OnPress func() error // Only applies when Label is used OpensMenu bool }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/panels/context_state.go
pkg/gui/panels/context_state.go
package panels import ( "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/samber/lo" ) // A 'context' generally corresponds to an item and the tab in the main panel that we're // displaying. So if we switch to a new item, or change the tab in the panel panel // for the current item, we end up with a new context. When we have a new context, // we render new content to the main panel. type ContextState[T any] struct { // index of the currently selected tab in the main view. mainTabIdx int // this function returns the tabs that we can display for an item (the tabs // are shown on the main view) GetMainTabs func() []MainTab[T] // This tells us whether we need to re-render to the main panel for a given item. // This should include the item's ID and if you want to invalidate the cache for // some other reason, you can add that to the key as well (e.g. the container's state). GetItemContextCacheKey func(item T) string } type MainTab[T any] struct { // key used as part of the context cache key Key string // title of the tab, rendered in the main view Title string // function to render the content of the tab Render func(item T) tasks.TaskFunc } func (self *ContextState[T]) GetMainTabTitles() []string { return lo.Map(self.GetMainTabs(), func(tab MainTab[T], _ int) string { return tab.Title }) } func (self *ContextState[T]) GetCurrentContextKey(item T) string { return self.GetItemContextCacheKey(item) + "-" + self.GetCurrentMainTab().Key } func (self *ContextState[T]) GetCurrentMainTab() MainTab[T] { return self.GetMainTabs()[self.mainTabIdx] } func (self *ContextState[T]) HandleNextMainTab() { tabs := self.GetMainTabs() if len(tabs) == 0 { return } self.mainTabIdx = (self.mainTabIdx + 1) % len(tabs) } func (self *ContextState[T]) HandlePrevMainTab() { tabs := self.GetMainTabs() if len(tabs) == 0 { return } self.mainTabIdx = (self.mainTabIdx - 1 + len(tabs)) % len(tabs) } func (self *ContextState[T]) SetMainTabIndex(index int) { self.mainTabIdx = index }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/panels/filtered_list.go
pkg/gui/panels/filtered_list.go
package panels import ( "sort" "sync" ) type FilteredList[T comparable] struct { allItems []T // indices of items in the allItems slice that are included in the filtered list indices []int mutex sync.RWMutex } func NewFilteredList[T comparable]() *FilteredList[T] { return &FilteredList[T]{} } func (self *FilteredList[T]) SetItems(items []T) { self.mutex.Lock() defer self.mutex.Unlock() self.allItems = items self.indices = make([]int, len(items)) for i := range self.indices { self.indices[i] = i } } func (self *FilteredList[T]) Filter(filter func(T, int) bool) { self.mutex.Lock() defer self.mutex.Unlock() self.indices = self.indices[:0] for i, item := range self.allItems { if filter(item, i) { self.indices = append(self.indices, i) } } } func (self *FilteredList[T]) Sort(less func(T, T) bool) { self.mutex.Lock() defer self.mutex.Unlock() if less == nil { return } sort.Slice(self.indices, func(i, j int) bool { return less(self.allItems[self.indices[i]], self.allItems[self.indices[j]]) }) } func (self *FilteredList[T]) Get(index int) T { self.mutex.RLock() defer self.mutex.RUnlock() return self.allItems[self.indices[index]] } func (self *FilteredList[T]) TryGet(index int) (T, bool) { self.mutex.RLock() defer self.mutex.RUnlock() if index < 0 || index >= len(self.indices) { var zero T return zero, false } return self.allItems[self.indices[index]], true } // returns the length of the filtered list func (self *FilteredList[T]) Len() int { self.mutex.RLock() defer self.mutex.RUnlock() return len(self.indices) } func (self *FilteredList[T]) GetIndex(item T) int { self.mutex.RLock() defer self.mutex.RUnlock() for i, index := range self.indices { if self.allItems[index] == item { return i } } return -1 } func (self *FilteredList[T]) GetItems() []T { self.mutex.RLock() defer self.mutex.RUnlock() result := make([]T, len(self.indices)) for i, index := range self.indices { result[i] = self.allItems[index] } return result } func (self *FilteredList[T]) GetAllItems() []T { self.mutex.RLock() defer self.mutex.RUnlock() return self.allItems }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/panels/list_panel.go
pkg/gui/panels/list_panel.go
package panels import ( "github.com/jesseduffield/gocui" lcUtils "github.com/jesseduffield/lazycore/pkg/utils" ) type ListPanel[T comparable] struct { SelectedIdx int List *FilteredList[T] View *gocui.View } func (self *ListPanel[T]) SetSelectedLineIdx(value int) { clampedValue := 0 if self.List.Len() > 0 { clampedValue = lcUtils.Clamp(value, 0, self.List.Len()-1) } self.SelectedIdx = clampedValue } func (self *ListPanel[T]) clampSelectedLineIdx() { clamped := lcUtils.Clamp(self.SelectedIdx, 0, self.List.Len()-1) if clamped != self.SelectedIdx { self.SelectedIdx = clamped } } // moves the cursor up or down by the given amount (up for negative values) func (self *ListPanel[T]) moveSelectedLine(delta int) { self.SetSelectedLineIdx(self.SelectedIdx + delta) } func (self *ListPanel[T]) SelectNextLine() { self.moveSelectedLine(1) } func (self *ListPanel[T]) SelectPrevLine() { self.moveSelectedLine(-1) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/panels/side_list_panel.go
pkg/gui/panels/side_list_panel.go
package panels import ( "context" "fmt" "strings" "github.com/go-errors/errors" "github.com/jesseduffield/gocui" "github.com/jesseduffield/lazydocker/pkg/tasks" "github.com/jesseduffield/lazydocker/pkg/utils" "github.com/samber/lo" ) type ISideListPanel interface { SetMainTabIndex(int) HandleSelect() error GetView() *gocui.View Refocus() RerenderList() error IsFilterDisabled() bool IsHidden() bool HandleNextLine() error HandlePrevLine() error HandleClick() error HandlePrevMainTab() error HandleNextMainTab() error } // list panel at the side of the screen that renders content to the main panel type SideListPanel[T comparable] struct { ContextState *ContextState[T] ListPanel[T] // message to render in the main view if there are no items in the panel // and it has focus. Leave empty if you don't want to render anything NoItemsMessage string // a representation of the gui Gui IGui // this Filter is applied on top of additional default filters Filter func(T) bool Sort func(a, b T) bool // a callback to invoke when the item is clicked OnClick func(T) error // returns the cells that we render to the view in a table format. The cells will // be rendered with padding. GetTableCells func(T) []string // function to be called after re-rendering list. Can be nil OnRerender func() error // set this to true if you don't want to allow manual filtering via '/' DisableFilter bool // This can be nil if you want to always show the panel Hide func() bool } var _ ISideListPanel = &SideListPanel[int]{} type IGui interface { HandleClick(v *gocui.View, itemCount int, selectedLine *int, handleSelect func() error) error NewSimpleRenderStringTask(getContent func() string) tasks.TaskFunc FocusY(selectedLine int, itemCount int, view *gocui.View) ShouldRefresh(contextKey string) bool GetMainView() *gocui.View IsCurrentView(*gocui.View) bool FilterString(view *gocui.View) string IgnoreStrings() []string Update(func() error) QueueTask(f func(ctx context.Context)) error } func (self *SideListPanel[T]) HandleClick() error { itemCount := self.List.Len() handleSelect := self.HandleSelect selectedLine := &self.SelectedIdx if err := self.Gui.HandleClick(self.View, itemCount, selectedLine, handleSelect); err != nil { return err } if self.OnClick != nil { selectedItem, err := self.GetSelectedItem() if err == nil { return self.OnClick(selectedItem) } } return nil } func (self *SideListPanel[T]) GetView() *gocui.View { return self.View } func (self *SideListPanel[T]) HandleSelect() error { item, err := self.GetSelectedItem() if err != nil { if err.Error() != self.NoItemsMessage { return err } if self.NoItemsMessage != "" { self.Gui.NewSimpleRenderStringTask(func() string { return self.NoItemsMessage }) } return nil } self.Refocus() return self.renderContext(item) } func (self *SideListPanel[T]) renderContext(item T) error { if self.ContextState == nil { return nil } key := self.ContextState.GetCurrentContextKey(item) if !self.Gui.ShouldRefresh(key) { return nil } mainView := self.Gui.GetMainView() mainView.Tabs = self.ContextState.GetMainTabTitles() mainView.TabIndex = self.ContextState.mainTabIdx task := self.ContextState.GetCurrentMainTab().Render(item) return self.Gui.QueueTask(task) } func (self *SideListPanel[T]) GetSelectedItem() (T, error) { var zero T item, ok := self.List.TryGet(self.SelectedIdx) if !ok { // could probably have a better error here return zero, errors.New(self.NoItemsMessage) } return item, nil } func (self *SideListPanel[T]) HandleNextLine() error { self.SelectNextLine() return self.HandleSelect() } func (self *SideListPanel[T]) HandlePrevLine() error { self.SelectPrevLine() return self.HandleSelect() } func (self *SideListPanel[T]) HandleNextMainTab() error { if self.ContextState == nil { return nil } self.ContextState.HandleNextMainTab() return self.HandleSelect() } func (self *SideListPanel[T]) HandlePrevMainTab() error { if self.ContextState == nil { return nil } self.ContextState.HandlePrevMainTab() return self.HandleSelect() } func (self *SideListPanel[T]) Refocus() { self.Gui.FocusY(self.SelectedIdx, self.List.Len(), self.View) } func (self *SideListPanel[T]) SetItems(items []T) { self.List.SetItems(items) self.FilterAndSort() } func (self *SideListPanel[T]) FilterAndSort() { filterString := self.Gui.FilterString(self.View) self.List.Filter(func(item T, index int) bool { if self.Filter != nil && !self.Filter(item) { return false } if lo.SomeBy(self.Gui.IgnoreStrings(), func(ignore string) bool { return lo.SomeBy(self.GetTableCells(item), func(searchString string) bool { return strings.Contains(searchString, ignore) }) }) { return false } if filterString != "" { return lo.SomeBy(self.GetTableCells(item), func(searchString string) bool { return strings.Contains(searchString, filterString) }) } return true }) self.List.Sort(self.Sort) self.clampSelectedLineIdx() } func (self *SideListPanel[T]) RerenderList() error { self.FilterAndSort() self.Gui.Update(func() error { self.View.Clear() table := lo.Map(self.List.GetItems(), func(item T, index int) []string { return self.GetTableCells(item) }) renderedTable, err := utils.RenderTable(table) if err != nil { return err } fmt.Fprint(self.View, renderedTable) if self.OnRerender != nil { if err := self.OnRerender(); err != nil { return err } } if self.Gui.IsCurrentView(self.View) { return self.HandleSelect() } return nil }) return nil } func (self *SideListPanel[T]) SetMainTabIndex(index int) { if self.ContextState == nil { return } self.ContextState.SetMainTabIndex(index) } func (self *SideListPanel[T]) IsFilterDisabled() bool { return self.DisableFilter } func (self *SideListPanel[T]) IsHidden() bool { if self.Hide == nil { return false } return self.Hide() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/pkg/gui/panels/filtered_list_test.go
pkg/gui/panels/filtered_list_test.go
package panels import ( "testing" "github.com/stretchr/testify/assert" ) func TestFilteredListGet(t *testing.T) { tests := []struct { f *FilteredList[int] args int want int }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: 1, want: 2, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: 2, want: 3, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{1}}, args: 0, want: 2, }, } for _, tt := range tests { if got := tt.f.Get(tt.args); got != tt.want { t.Errorf("FilteredList.Get() = %v, want %v", got, tt.want) } } } func TestFilteredListLen(t *testing.T) { tests := []struct { f *FilteredList[int] want int }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, want: 3, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{1}}, want: 1, }, } for _, tt := range tests { if got := tt.f.Len(); got != tt.want { t.Errorf("FilteredList.Len() = %v, want %v", got, tt.want) } } } func TestFilteredListFilter(t *testing.T) { tests := []struct { f *FilteredList[int] args func(int, int) bool want *FilteredList[int] }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: func(i int, _ int) bool { return i%2 == 0 }, want: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{1}}, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: func(i int, _ int) bool { return i%2 == 1 }, want: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 2}}, }, } for _, tt := range tests { tt.f.Filter(tt.args) assert.EqualValues(t, tt.f.indices, tt.want.indices) } } func TestFilteredListSort(t *testing.T) { tests := []struct { f *FilteredList[int] args func(int, int) bool want *FilteredList[int] }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: func(i int, j int) bool { return i < j }, want: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: func(i int, j int) bool { return i > j }, want: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{2, 1, 0}}, }, } for _, tt := range tests { tt.f.Sort(tt.args) assert.EqualValues(t, tt.f.indices, tt.want.indices) } } func TestFilteredListGetIndex(t *testing.T) { tests := []struct { f *FilteredList[int] args int want int }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: 1, want: 0, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: 2, want: 1, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{1}}, args: 0, want: -1, }, } for _, tt := range tests { if got := tt.f.GetIndex(tt.args); got != tt.want { t.Errorf("FilteredList.GetIndex() = %v, want %v", got, tt.want) } } } func TestFilteredListGetItems(t *testing.T) { tests := []struct { f *FilteredList[int] want []int }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, want: []int{1, 2, 3}, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{1}}, want: []int{2}, }, } for _, tt := range tests { got := tt.f.GetItems() assert.EqualValues(t, got, tt.want) } } func TestFilteredListSetItems(t *testing.T) { tests := []struct { f *FilteredList[int] args []int want *FilteredList[int] }{ { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{0, 1, 2}}, args: []int{4, 5, 6}, want: &FilteredList[int]{allItems: []int{4, 5, 6}, indices: []int{0, 1, 2}}, }, { f: &FilteredList[int]{allItems: []int{1, 2, 3}, indices: []int{1}}, args: []int{4}, want: &FilteredList[int]{allItems: []int{4}, indices: []int{0}}, }, } for _, tt := range tests { tt.f.SetItems(tt.args) assert.EqualValues(t, tt.f.indices, tt.want.indices) assert.EqualValues(t, tt.f.allItems, tt.want.allItems) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/assertion_format.go
vendor/github.com/stretchr/testify/assert/assertion_format.go
// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package assert import ( http "net/http" url "net/url" time "time" ) // Conditionf uses a Comparison to assert a complex condition. func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Condition(t, comp, append([]interface{}{msg}, args...)...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") // assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") // assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Contains(t, s, contains, append([]interface{}{msg}, args...)...) } // DirExistsf checks whether a directory exists in the given path. It also fails // if the path is a file rather a directory or there is an error checking whether it exists. func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return DirExists(t, path, append([]interface{}{msg}, args...)...) } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Empty(t, object, append([]interface{}{msg}, args...)...) } // Equalf asserts that two objects are equal. // // assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) } // EqualExportedValuesf asserts that the types of two objects are equal and their public // fields are also equal. This is useful for comparing structs that have private fields // that could potentially differ. // // type S struct { // Exported int // notExported int // } // assert.EqualExportedValuesf(t, S{1, 2}, S{1, 3}, "error message %s", "formatted") => true // assert.EqualExportedValuesf(t, S{1, 2}, S{2, 3}, "error message %s", "formatted") => false func EqualExportedValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualExportedValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // EqualValuesf asserts that two objects are equal or convertible to the same types // and equal. // // assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Errorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Error(t, err, append([]interface{}{msg}, args...)...) } // ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. // This is a wrapper for errors.As. func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ErrorAs(t, err, target, append([]interface{}{msg}, args...)...) } // ErrorContainsf asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // // actualObj, err := SomeFunction() // assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ErrorContains(t, theError, contains, append([]interface{}{msg}, args...)...) } // ErrorIsf asserts that at least one of the errors in err's chain matches target. // This is a wrapper for errors.Is. func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ErrorIs(t, err, target, append([]interface{}{msg}, args...)...) } // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // // assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Eventually(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) } // EventuallyWithTf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. In contrast to Eventually, // it supplies a CollectT to the condition function, so that the condition // function can use the CollectT to call other assertions. // The condition is considered "met" if no errors are raised in a tick. // The supplied CollectT collects all errors from one tick (if there are any). // If the condition is not met before waitFor, the collected errors of // the last tick are copied to t. // // externalValue := false // go func() { // time.Sleep(8*time.Second) // externalValue = true // }() // assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") // }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EventuallyWithT(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) } // Exactlyf asserts that two objects are equal in value and type. // // assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) } // Failf reports a failure through func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) } // FailNowf fails test func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) } // Falsef asserts that the specified value is false. // // assert.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return False(t, value, append([]interface{}{msg}, args...)...) } // FileExistsf checks whether a file exists in the given path. It also fails if // the path points to a directory or there is an error when trying to check the file. func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return FileExists(t, path, append([]interface{}{msg}, args...)...) } // Greaterf asserts that the first element is greater than the second // // assert.Greaterf(t, 2, 1, "error message %s", "formatted") // assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") // assert.Greaterf(t, "b", "a", "error message %s", "formatted") func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Greater(t, e1, e2, append([]interface{}{msg}, args...)...) } // GreaterOrEqualf asserts that the first element is greater than or equal to the second // // assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") // assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") // assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") // assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return GreaterOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) } // HTTPErrorf asserts that a specified handler returns an error status code. // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // HTTPStatusCodef asserts that a specified handler returns a specified status code. // // assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPStatusCode(t, handler, method, url, values, statuscode, append([]interface{}{msg}, args...)...) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // Implementsf asserts that an object is implemented by the specified interface. // // assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) } // InDeltaf asserts that the two numerals are within delta of each other. // // assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // IsDecreasingf asserts that the collection is decreasing // // assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") // assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") // assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsDecreasing(t, object, append([]interface{}{msg}, args...)...) } // IsIncreasingf asserts that the collection is increasing // // assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") // assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") // assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsIncreasing(t, object, append([]interface{}{msg}, args...)...) } // IsNonDecreasingf asserts that the collection is not decreasing // // assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") // assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") // assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsNonDecreasing(t, object, append([]interface{}{msg}, args...)...) } // IsNonIncreasingf asserts that the collection is not increasing // // assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") // assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") // assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsNonIncreasing(t, object, append([]interface{}{msg}, args...)...) } // IsTypef asserts that the specified objects are of the same type. func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) } // JSONEqf asserts that two JSON strings are equivalent. // // assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // assert.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Len(t, object, length, append([]interface{}{msg}, args...)...) } // Lessf asserts that the first element is less than the second // // assert.Lessf(t, 1, 2, "error message %s", "formatted") // assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") // assert.Lessf(t, "a", "b", "error message %s", "formatted") func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Less(t, e1, e2, append([]interface{}{msg}, args...)...) } // LessOrEqualf asserts that the first element is less than or equal to the second // // assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") // assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") // assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") // assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return LessOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...) } // Negativef asserts that the specified element is negative // // assert.Negativef(t, -1, "error message %s", "formatted") // assert.Negativef(t, -1.23, "error message %s", "formatted") func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Negative(t, e, append([]interface{}{msg}, args...)...) } // Neverf asserts that the given condition doesn't satisfy in waitFor time, // periodically checking the target function each tick. // // assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Never(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) } // Nilf asserts that the specified object is nil. // // assert.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Nil(t, object, append([]interface{}{msg}, args...)...) } // NoDirExistsf checks whether a directory does not exist in the given path. // It fails if the path points to an existing _directory_ only. func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoDirExists(t, path, append([]interface{}{msg}, args...)...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoErrorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoError(t, err, append([]interface{}{msg}, args...)...) } // NoFileExistsf checks whether a file does not exist in a given path. It fails // if the path points to an existing _file_ only. func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoFileExists(t, path, append([]interface{}{msg}, args...)...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") // assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") // assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmptyf(t, obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEmpty(t, object, append([]interface{}{msg}, args...)...) } // NotEqualf asserts that the specified values are NOT equal. // // assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotEqualValuesf asserts that two objects are not equal even when converted to the same type // // assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotErrorIsf asserts that at none of the errors in err's chain matches target. // This is a wrapper for errors.Is. func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotErrorIs(t, err, target, append([]interface{}{msg}, args...)...) } // NotImplementsf asserts that an object does not implement the specified interface. // // assert.NotImplementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func NotImplementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotImplements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) } // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotNil(t, object, append([]interface{}{msg}, args...)...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotPanics(t, f, append([]interface{}{msg}, args...)...) } // NotRegexpf asserts that a specified regexp does not match a string. // // assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) } // NotSamef asserts that two pointers do not reference the same object. // // assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotSubsetf asserts that the specified list(array, slice...) or map does NOT // contain all elements given in the specified subset list(array, slice...) or // map. // // assert.NotSubsetf(t, [1, 3, 4], [1, 2], "error message %s", "formatted") // assert.NotSubsetf(t, {"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) } // NotZerof asserts that i is not the zero value for its type. func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotZero(t, i, append([]interface{}{msg}, args...)...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Panics(t, f, append([]interface{}{msg}, args...)...) } // PanicsWithErrorf asserts that the code inside the specified PanicTestFunc // panics, and that the recovered panic value is an error that satisfies the // EqualError comparison. // // assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return PanicsWithError(t, errString, f, append([]interface{}{msg}, args...)...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) } // Positivef asserts that the specified element is positive // // assert.Positivef(t, 1, "error message %s", "formatted") // assert.Positivef(t, 1.23, "error message %s", "formatted") func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Positive(t, e, append([]interface{}{msg}, args...)...) } // Regexpf asserts that a specified regexp matches a string. // // assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) } // Samef asserts that two pointers reference the same object. // // assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Same(t, expected, actual, append([]interface{}{msg}, args...)...) } // Subsetf asserts that the specified list(array, slice...) or map contains all // elements given in the specified subset list(array, slice...) or map. // // assert.Subsetf(t, [1, 2, 3], [1, 2], "error message %s", "formatted") // assert.Subsetf(t, {"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Subset(t, list, subset, append([]interface{}{msg}, args...)...) } // Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return True(t, value, append([]interface{}{msg}, args...)...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // WithinRangef asserts that a time is within a time range (inclusive). // // assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return WithinRange(t, actual, start, end, append([]interface{}{msg}, args...)...) } // YAMLEqf asserts that two YAML strings are equivalent.
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/assertion_forward.go
vendor/github.com/stretchr/testify/assert/assertion_forward.go
// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT. package assert import ( http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Condition(a.t, comp, msgAndArgs...) } // Conditionf uses a Comparison to assert a complex condition. func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Conditionf(a.t, comp, msg, args...) } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Contains("Hello World", "World") // a.Contains(["Hello", "World"], "World") // a.Contains({"Hello": "World"}, "Hello") func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Contains(a.t, s, contains, msgAndArgs...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Containsf("Hello World", "World", "error message %s", "formatted") // a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") // a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Containsf(a.t, s, contains, msg, args...) } // DirExists checks whether a directory exists in the given path. It also fails // if the path is a file rather a directory or there is an error checking whether it exists. func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return DirExists(a.t, path, msgAndArgs...) } // DirExistsf checks whether a directory exists in the given path. It also fails // if the path is a file rather a directory or there is an error checking whether it exists. func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return DirExistsf(a.t, path, msg, args...) } // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ElementsMatch(a.t, listA, listB, msgAndArgs...) } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ElementsMatchf(a.t, listA, listB, msg, args...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Empty(obj) func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Empty(a.t, object, msgAndArgs...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Emptyf(obj, "error message %s", "formatted") func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Emptyf(a.t, object, msg, args...) } // Equal asserts that two objects are equal. // // a.Equal(123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Equal(a.t, expected, actual, msgAndArgs...) } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualError(err, expectedErrorString) func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualError(a.t, theError, errString, msgAndArgs...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualErrorf(a.t, theError, errString, msg, args...) } // EqualExportedValues asserts that the types of two objects are equal and their public // fields are also equal. This is useful for comparing structs that have private fields // that could potentially differ. // // type S struct { // Exported int // notExported int // } // a.EqualExportedValues(S{1, 2}, S{1, 3}) => true // a.EqualExportedValues(S{1, 2}, S{2, 3}) => false func (a *Assertions) EqualExportedValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualExportedValues(a.t, expected, actual, msgAndArgs...) } // EqualExportedValuesf asserts that the types of two objects are equal and their public // fields are also equal. This is useful for comparing structs that have private fields // that could potentially differ. // // type S struct { // Exported int // notExported int // } // a.EqualExportedValuesf(S{1, 2}, S{1, 3}, "error message %s", "formatted") => true // a.EqualExportedValuesf(S{1, 2}, S{2, 3}, "error message %s", "formatted") => false func (a *Assertions) EqualExportedValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualExportedValuesf(a.t, expected, actual, msg, args...) } // EqualValues asserts that two objects are equal or convertible to the same types // and equal. // // a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualValues(a.t, expected, actual, msgAndArgs...) } // EqualValuesf asserts that two objects are equal or convertible to the same types // and equal. // // a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualValuesf(a.t, expected, actual, msg, args...) } // Equalf asserts that two objects are equal. // // a.Equalf(123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Equalf(a.t, expected, actual, msg, args...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Error(err) { // assert.Equal(t, expectedError, err) // } func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Error(a.t, err, msgAndArgs...) } // ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. // This is a wrapper for errors.As. func (a *Assertions) ErrorAs(err error, target interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ErrorAs(a.t, err, target, msgAndArgs...) } // ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. // This is a wrapper for errors.As. func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ErrorAsf(a.t, err, target, msg, args...) } // ErrorContains asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // // actualObj, err := SomeFunction() // a.ErrorContains(err, expectedErrorSubString) func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ErrorContains(a.t, theError, contains, msgAndArgs...) } // ErrorContainsf asserts that a function returned an error (i.e. not `nil`) // and that the error contains the specified substring. // // actualObj, err := SomeFunction() // a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") func (a *Assertions) ErrorContainsf(theError error, contains string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ErrorContainsf(a.t, theError, contains, msg, args...) } // ErrorIs asserts that at least one of the errors in err's chain matches target. // This is a wrapper for errors.Is. func (a *Assertions) ErrorIs(err error, target error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ErrorIs(a.t, err, target, msgAndArgs...) } // ErrorIsf asserts that at least one of the errors in err's chain matches target. // This is a wrapper for errors.Is. func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ErrorIsf(a.t, err, target, msg, args...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Errorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Errorf(a.t, err, msg, args...) } // Eventually asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // // a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Eventually(a.t, condition, waitFor, tick, msgAndArgs...) } // EventuallyWithT asserts that given condition will be met in waitFor time, // periodically checking target function each tick. In contrast to Eventually, // it supplies a CollectT to the condition function, so that the condition // function can use the CollectT to call other assertions. // The condition is considered "met" if no errors are raised in a tick. // The supplied CollectT collects all errors from one tick (if there are any). // If the condition is not met before waitFor, the collected errors of // the last tick are copied to t. // // externalValue := false // go func() { // time.Sleep(8*time.Second) // externalValue = true // }() // a.EventuallyWithT(func(c *assert.CollectT) { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") // }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EventuallyWithT(a.t, condition, waitFor, tick, msgAndArgs...) } // EventuallyWithTf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. In contrast to Eventually, // it supplies a CollectT to the condition function, so that the condition // function can use the CollectT to call other assertions. // The condition is considered "met" if no errors are raised in a tick. // The supplied CollectT collects all errors from one tick (if there are any). // If the condition is not met before waitFor, the collected errors of // the last tick are copied to t. // // externalValue := false // go func() { // time.Sleep(8*time.Second) // externalValue = true // }() // a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") { // // add assertions as needed; any assertion failure will fail the current tick // assert.True(c, externalValue, "expected 'externalValue' to be true") // }, 1*time.Second, 10*time.Second, "external state has not changed to 'true'; still false") func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EventuallyWithTf(a.t, condition, waitFor, tick, msg, args...) } // Eventuallyf asserts that given condition will be met in waitFor time, // periodically checking target function each tick. // // a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Eventuallyf(a.t, condition, waitFor, tick, msg, args...) } // Exactly asserts that two objects are equal in value and type. // // a.Exactly(int32(123), int64(123)) func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Exactly(a.t, expected, actual, msgAndArgs...) } // Exactlyf asserts that two objects are equal in value and type. // // a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Exactlyf(a.t, expected, actual, msg, args...) } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Fail(a.t, failureMessage, msgAndArgs...) } // FailNow fails test func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FailNow(a.t, failureMessage, msgAndArgs...) } // FailNowf fails test func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FailNowf(a.t, failureMessage, msg, args...) } // Failf reports a failure through func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Failf(a.t, failureMessage, msg, args...) } // False asserts that the specified value is false. // // a.False(myBool) func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return False(a.t, value, msgAndArgs...) } // Falsef asserts that the specified value is false. // // a.Falsef(myBool, "error message %s", "formatted") func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Falsef(a.t, value, msg, args...) } // FileExists checks whether a file exists in the given path. It also fails if // the path points to a directory or there is an error when trying to check the file. func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FileExists(a.t, path, msgAndArgs...) } // FileExistsf checks whether a file exists in the given path. It also fails if // the path points to a directory or there is an error when trying to check the file. func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FileExistsf(a.t, path, msg, args...) } // Greater asserts that the first element is greater than the second // // a.Greater(2, 1) // a.Greater(float64(2), float64(1)) // a.Greater("b", "a") func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Greater(a.t, e1, e2, msgAndArgs...) } // GreaterOrEqual asserts that the first element is greater than or equal to the second // // a.GreaterOrEqual(2, 1) // a.GreaterOrEqual(2, 2) // a.GreaterOrEqual("b", "a") // a.GreaterOrEqual("b", "b") func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return GreaterOrEqual(a.t, e1, e2, msgAndArgs...) } // GreaterOrEqualf asserts that the first element is greater than or equal to the second // // a.GreaterOrEqualf(2, 1, "error message %s", "formatted") // a.GreaterOrEqualf(2, 2, "error message %s", "formatted") // a.GreaterOrEqualf("b", "a", "error message %s", "formatted") // a.GreaterOrEqualf("b", "b", "error message %s", "formatted") func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return GreaterOrEqualf(a.t, e1, e2, msg, args...) } // Greaterf asserts that the first element is greater than the second // // a.Greaterf(2, 1, "error message %s", "formatted") // a.Greaterf(float64(2), float64(1), "error message %s", "formatted") // a.Greaterf("b", "a", "error message %s", "formatted") func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Greaterf(a.t, e1, e2, msg, args...) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) } // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPError(a.t, handler, method, url, values, msgAndArgs...) } // HTTPErrorf asserts that a specified handler returns an error status code. // // a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPErrorf(a.t, handler, method, url, values, msg, args...) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPRedirectf(a.t, handler, method, url, values, msg, args...) } // HTTPStatusCode asserts that a specified handler returns a specified status code. // // a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...) } // HTTPStatusCodef asserts that a specified handler returns a specified status code. // // a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...) } // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPSuccessf(a.t, handler, method, url, values, msg, args...) } // Implements asserts that an object is implemented by the specified interface. // // a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Implements(a.t, interfaceObject, object, msgAndArgs...) } // Implementsf asserts that an object is implemented by the specified interface. // // a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Implementsf(a.t, interfaceObject, object, msg, args...) } // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, 22/7.0, 0.01) func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) } // InDeltaSlice is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) } // InDeltaf asserts that the two numerals are within delta of each other. // // a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaf(a.t, expected, actual, delta, msg, args...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) } // IsDecreasing asserts that the collection is decreasing // // a.IsDecreasing([]int{2, 1, 0}) // a.IsDecreasing([]float{2, 1}) // a.IsDecreasing([]string{"b", "a"}) func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsDecreasing(a.t, object, msgAndArgs...) } // IsDecreasingf asserts that the collection is decreasing // // a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") // a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") // a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsDecreasingf(a.t, object, msg, args...) } // IsIncreasing asserts that the collection is increasing // // a.IsIncreasing([]int{1, 2, 3}) // a.IsIncreasing([]float{1, 2}) // a.IsIncreasing([]string{"a", "b"}) func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsIncreasing(a.t, object, msgAndArgs...) } // IsIncreasingf asserts that the collection is increasing // // a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") // a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") // a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsIncreasingf(a.t, object, msg, args...) } // IsNonDecreasing asserts that the collection is not decreasing // // a.IsNonDecreasing([]int{1, 1, 2}) // a.IsNonDecreasing([]float{1, 2}) // a.IsNonDecreasing([]string{"a", "b"}) func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsNonDecreasing(a.t, object, msgAndArgs...) } // IsNonDecreasingf asserts that the collection is not decreasing // // a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") // a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") // a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsNonDecreasingf(a.t, object, msg, args...) } // IsNonIncreasing asserts that the collection is not increasing // // a.IsNonIncreasing([]int{2, 1, 1}) // a.IsNonIncreasing([]float{2, 1}) // a.IsNonIncreasing([]string{"b", "a"}) func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsNonIncreasing(a.t, object, msgAndArgs...) } // IsNonIncreasingf asserts that the collection is not increasing // // a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted")
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/forward_assertions.go
vendor/github.com/stretchr/testify/assert/forward_assertions.go
package assert // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/errors.go
vendor/github.com/stretchr/testify/assert/errors.go
package assert import ( "errors" ) // AnError is an error instance useful for testing. If the code does not care // about error specifics, and only needs to return the error for example, this // error should be used to make the test code more readable. var AnError = errors.New("assert.AnError general error for testing")
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/assertion_compare.go
vendor/github.com/stretchr/testify/assert/assertion_compare.go
package assert import ( "bytes" "fmt" "reflect" "time" ) type CompareType int const ( compareLess CompareType = iota - 1 compareEqual compareGreater ) var ( intType = reflect.TypeOf(int(1)) int8Type = reflect.TypeOf(int8(1)) int16Type = reflect.TypeOf(int16(1)) int32Type = reflect.TypeOf(int32(1)) int64Type = reflect.TypeOf(int64(1)) uintType = reflect.TypeOf(uint(1)) uint8Type = reflect.TypeOf(uint8(1)) uint16Type = reflect.TypeOf(uint16(1)) uint32Type = reflect.TypeOf(uint32(1)) uint64Type = reflect.TypeOf(uint64(1)) uintptrType = reflect.TypeOf(uintptr(1)) float32Type = reflect.TypeOf(float32(1)) float64Type = reflect.TypeOf(float64(1)) stringType = reflect.TypeOf("") timeType = reflect.TypeOf(time.Time{}) bytesType = reflect.TypeOf([]byte{}) ) func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { obj1Value := reflect.ValueOf(obj1) obj2Value := reflect.ValueOf(obj2) // throughout this switch we try and avoid calling .Convert() if possible, // as this has a pretty big performance impact switch kind { case reflect.Int: { intobj1, ok := obj1.(int) if !ok { intobj1 = obj1Value.Convert(intType).Interface().(int) } intobj2, ok := obj2.(int) if !ok { intobj2 = obj2Value.Convert(intType).Interface().(int) } if intobj1 > intobj2 { return compareGreater, true } if intobj1 == intobj2 { return compareEqual, true } if intobj1 < intobj2 { return compareLess, true } } case reflect.Int8: { int8obj1, ok := obj1.(int8) if !ok { int8obj1 = obj1Value.Convert(int8Type).Interface().(int8) } int8obj2, ok := obj2.(int8) if !ok { int8obj2 = obj2Value.Convert(int8Type).Interface().(int8) } if int8obj1 > int8obj2 { return compareGreater, true } if int8obj1 == int8obj2 { return compareEqual, true } if int8obj1 < int8obj2 { return compareLess, true } } case reflect.Int16: { int16obj1, ok := obj1.(int16) if !ok { int16obj1 = obj1Value.Convert(int16Type).Interface().(int16) } int16obj2, ok := obj2.(int16) if !ok { int16obj2 = obj2Value.Convert(int16Type).Interface().(int16) } if int16obj1 > int16obj2 { return compareGreater, true } if int16obj1 == int16obj2 { return compareEqual, true } if int16obj1 < int16obj2 { return compareLess, true } } case reflect.Int32: { int32obj1, ok := obj1.(int32) if !ok { int32obj1 = obj1Value.Convert(int32Type).Interface().(int32) } int32obj2, ok := obj2.(int32) if !ok { int32obj2 = obj2Value.Convert(int32Type).Interface().(int32) } if int32obj1 > int32obj2 { return compareGreater, true } if int32obj1 == int32obj2 { return compareEqual, true } if int32obj1 < int32obj2 { return compareLess, true } } case reflect.Int64: { int64obj1, ok := obj1.(int64) if !ok { int64obj1 = obj1Value.Convert(int64Type).Interface().(int64) } int64obj2, ok := obj2.(int64) if !ok { int64obj2 = obj2Value.Convert(int64Type).Interface().(int64) } if int64obj1 > int64obj2 { return compareGreater, true } if int64obj1 == int64obj2 { return compareEqual, true } if int64obj1 < int64obj2 { return compareLess, true } } case reflect.Uint: { uintobj1, ok := obj1.(uint) if !ok { uintobj1 = obj1Value.Convert(uintType).Interface().(uint) } uintobj2, ok := obj2.(uint) if !ok { uintobj2 = obj2Value.Convert(uintType).Interface().(uint) } if uintobj1 > uintobj2 { return compareGreater, true } if uintobj1 == uintobj2 { return compareEqual, true } if uintobj1 < uintobj2 { return compareLess, true } } case reflect.Uint8: { uint8obj1, ok := obj1.(uint8) if !ok { uint8obj1 = obj1Value.Convert(uint8Type).Interface().(uint8) } uint8obj2, ok := obj2.(uint8) if !ok { uint8obj2 = obj2Value.Convert(uint8Type).Interface().(uint8) } if uint8obj1 > uint8obj2 { return compareGreater, true } if uint8obj1 == uint8obj2 { return compareEqual, true } if uint8obj1 < uint8obj2 { return compareLess, true } } case reflect.Uint16: { uint16obj1, ok := obj1.(uint16) if !ok { uint16obj1 = obj1Value.Convert(uint16Type).Interface().(uint16) } uint16obj2, ok := obj2.(uint16) if !ok { uint16obj2 = obj2Value.Convert(uint16Type).Interface().(uint16) } if uint16obj1 > uint16obj2 { return compareGreater, true } if uint16obj1 == uint16obj2 { return compareEqual, true } if uint16obj1 < uint16obj2 { return compareLess, true } } case reflect.Uint32: { uint32obj1, ok := obj1.(uint32) if !ok { uint32obj1 = obj1Value.Convert(uint32Type).Interface().(uint32) } uint32obj2, ok := obj2.(uint32) if !ok { uint32obj2 = obj2Value.Convert(uint32Type).Interface().(uint32) } if uint32obj1 > uint32obj2 { return compareGreater, true } if uint32obj1 == uint32obj2 { return compareEqual, true } if uint32obj1 < uint32obj2 { return compareLess, true } } case reflect.Uint64: { uint64obj1, ok := obj1.(uint64) if !ok { uint64obj1 = obj1Value.Convert(uint64Type).Interface().(uint64) } uint64obj2, ok := obj2.(uint64) if !ok { uint64obj2 = obj2Value.Convert(uint64Type).Interface().(uint64) } if uint64obj1 > uint64obj2 { return compareGreater, true } if uint64obj1 == uint64obj2 { return compareEqual, true } if uint64obj1 < uint64obj2 { return compareLess, true } } case reflect.Float32: { float32obj1, ok := obj1.(float32) if !ok { float32obj1 = obj1Value.Convert(float32Type).Interface().(float32) } float32obj2, ok := obj2.(float32) if !ok { float32obj2 = obj2Value.Convert(float32Type).Interface().(float32) } if float32obj1 > float32obj2 { return compareGreater, true } if float32obj1 == float32obj2 { return compareEqual, true } if float32obj1 < float32obj2 { return compareLess, true } } case reflect.Float64: { float64obj1, ok := obj1.(float64) if !ok { float64obj1 = obj1Value.Convert(float64Type).Interface().(float64) } float64obj2, ok := obj2.(float64) if !ok { float64obj2 = obj2Value.Convert(float64Type).Interface().(float64) } if float64obj1 > float64obj2 { return compareGreater, true } if float64obj1 == float64obj2 { return compareEqual, true } if float64obj1 < float64obj2 { return compareLess, true } } case reflect.String: { stringobj1, ok := obj1.(string) if !ok { stringobj1 = obj1Value.Convert(stringType).Interface().(string) } stringobj2, ok := obj2.(string) if !ok { stringobj2 = obj2Value.Convert(stringType).Interface().(string) } if stringobj1 > stringobj2 { return compareGreater, true } if stringobj1 == stringobj2 { return compareEqual, true } if stringobj1 < stringobj2 { return compareLess, true } } // Check for known struct types we can check for compare results. case reflect.Struct: { // All structs enter here. We're not interested in most types. if !obj1Value.CanConvert(timeType) { break } // time.Time can be compared! timeObj1, ok := obj1.(time.Time) if !ok { timeObj1 = obj1Value.Convert(timeType).Interface().(time.Time) } timeObj2, ok := obj2.(time.Time) if !ok { timeObj2 = obj2Value.Convert(timeType).Interface().(time.Time) } return compare(timeObj1.UnixNano(), timeObj2.UnixNano(), reflect.Int64) } case reflect.Slice: { // We only care about the []byte type. if !obj1Value.CanConvert(bytesType) { break } // []byte can be compared! bytesObj1, ok := obj1.([]byte) if !ok { bytesObj1 = obj1Value.Convert(bytesType).Interface().([]byte) } bytesObj2, ok := obj2.([]byte) if !ok { bytesObj2 = obj2Value.Convert(bytesType).Interface().([]byte) } return CompareType(bytes.Compare(bytesObj1, bytesObj2)), true } case reflect.Uintptr: { uintptrObj1, ok := obj1.(uintptr) if !ok { uintptrObj1 = obj1Value.Convert(uintptrType).Interface().(uintptr) } uintptrObj2, ok := obj2.(uintptr) if !ok { uintptrObj2 = obj2Value.Convert(uintptrType).Interface().(uintptr) } if uintptrObj1 > uintptrObj2 { return compareGreater, true } if uintptrObj1 == uintptrObj2 { return compareEqual, true } if uintptrObj1 < uintptrObj2 { return compareLess, true } } } return compareEqual, false } // Greater asserts that the first element is greater than the second // // assert.Greater(t, 2, 1) // assert.Greater(t, float64(2), float64(1)) // assert.Greater(t, "b", "a") func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) } // GreaterOrEqual asserts that the first element is greater than or equal to the second // // assert.GreaterOrEqual(t, 2, 1) // assert.GreaterOrEqual(t, 2, 2) // assert.GreaterOrEqual(t, "b", "a") // assert.GreaterOrEqual(t, "b", "b") func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) } // Less asserts that the first element is less than the second // // assert.Less(t, 1, 2) // assert.Less(t, float64(1), float64(2)) // assert.Less(t, "a", "b") func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) } // LessOrEqual asserts that the first element is less than or equal to the second // // assert.LessOrEqual(t, 1, 2) // assert.LessOrEqual(t, 2, 2) // assert.LessOrEqual(t, "a", "b") // assert.LessOrEqual(t, "b", "b") func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) } // Positive asserts that the specified element is positive // // assert.Positive(t, 1) // assert.Positive(t, 1.23) func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } zero := reflect.Zero(reflect.TypeOf(e)) return compareTwoValues(t, e, zero.Interface(), []CompareType{compareGreater}, "\"%v\" is not positive", msgAndArgs...) } // Negative asserts that the specified element is negative // // assert.Negative(t, -1) // assert.Negative(t, -1.23) func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } zero := reflect.Zero(reflect.TypeOf(e)) return compareTwoValues(t, e, zero.Interface(), []CompareType{compareLess}, "\"%v\" is not negative", msgAndArgs...) } func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } e1Kind := reflect.ValueOf(e1).Kind() e2Kind := reflect.ValueOf(e2).Kind() if e1Kind != e2Kind { return Fail(t, "Elements should be the same type", msgAndArgs...) } compareResult, isComparable := compare(e1, e2, e1Kind) if !isComparable { return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) } if !containsValue(allowedComparesResults, compareResult) { return Fail(t, fmt.Sprintf(failMessage, e1, e2), msgAndArgs...) } return true } func containsValue(values []CompareType, value CompareType) bool { for _, v := range values { if v == value { return true } } return false }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/assertions.go
vendor/github.com/stretchr/testify/assert/assertions.go
package assert import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "math" "os" "reflect" "regexp" "runtime" "runtime/debug" "strings" "time" "unicode" "unicode/utf8" "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" "gopkg.in/yaml.v3" ) //go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl" // TestingT is an interface wrapper around *testing.T type TestingT interface { Errorf(format string, args ...interface{}) } // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful // for table driven tests. type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful // for table driven tests. type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful // for table driven tests. type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool // ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful // for table driven tests. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool // Comparison is a custom function that returns true on success and false on failure type Comparison func() (success bool) /* Helper functions */ // ObjectsAreEqual determines if two objects are considered equal. // // This function does no assertion of any kind. func ObjectsAreEqual(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } exp, ok := expected.([]byte) if !ok { return reflect.DeepEqual(expected, actual) } act, ok := actual.([]byte) if !ok { return false } if exp == nil || act == nil { return exp == nil && act == nil } return bytes.Equal(exp, act) } // copyExportedFields iterates downward through nested data structures and creates a copy // that only contains the exported struct fields. func copyExportedFields(expected interface{}) interface{} { if isNil(expected) { return expected } expectedType := reflect.TypeOf(expected) expectedKind := expectedType.Kind() expectedValue := reflect.ValueOf(expected) switch expectedKind { case reflect.Struct: result := reflect.New(expectedType).Elem() for i := 0; i < expectedType.NumField(); i++ { field := expectedType.Field(i) isExported := field.IsExported() if isExported { fieldValue := expectedValue.Field(i) if isNil(fieldValue) || isNil(fieldValue.Interface()) { continue } newValue := copyExportedFields(fieldValue.Interface()) result.Field(i).Set(reflect.ValueOf(newValue)) } } return result.Interface() case reflect.Ptr: result := reflect.New(expectedType.Elem()) unexportedRemoved := copyExportedFields(expectedValue.Elem().Interface()) result.Elem().Set(reflect.ValueOf(unexportedRemoved)) return result.Interface() case reflect.Array, reflect.Slice: var result reflect.Value if expectedKind == reflect.Array { result = reflect.New(reflect.ArrayOf(expectedValue.Len(), expectedType.Elem())).Elem() } else { result = reflect.MakeSlice(expectedType, expectedValue.Len(), expectedValue.Len()) } for i := 0; i < expectedValue.Len(); i++ { index := expectedValue.Index(i) if isNil(index) { continue } unexportedRemoved := copyExportedFields(index.Interface()) result.Index(i).Set(reflect.ValueOf(unexportedRemoved)) } return result.Interface() case reflect.Map: result := reflect.MakeMap(expectedType) for _, k := range expectedValue.MapKeys() { index := expectedValue.MapIndex(k) unexportedRemoved := copyExportedFields(index.Interface()) result.SetMapIndex(k, reflect.ValueOf(unexportedRemoved)) } return result.Interface() default: return expected } } // ObjectsExportedFieldsAreEqual determines if the exported (public) fields of two objects are // considered equal. This comparison of only exported fields is applied recursively to nested data // structures. // // This function does no assertion of any kind. // // Deprecated: Use [EqualExportedValues] instead. func ObjectsExportedFieldsAreEqual(expected, actual interface{}) bool { expectedCleaned := copyExportedFields(expected) actualCleaned := copyExportedFields(actual) return ObjectsAreEqualValues(expectedCleaned, actualCleaned) } // ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal. func ObjectsAreEqualValues(expected, actual interface{}) bool { if ObjectsAreEqual(expected, actual) { return true } expectedValue := reflect.ValueOf(expected) actualValue := reflect.ValueOf(actual) if !expectedValue.IsValid() || !actualValue.IsValid() { return false } expectedType := expectedValue.Type() actualType := actualValue.Type() if !expectedType.ConvertibleTo(actualType) { return false } if !isNumericType(expectedType) || !isNumericType(actualType) { // Attempt comparison after type conversion return reflect.DeepEqual( expectedValue.Convert(actualType).Interface(), actual, ) } // If BOTH values are numeric, there are chances of false positives due // to overflow or underflow. So, we need to make sure to always convert // the smaller type to a larger type before comparing. if expectedType.Size() >= actualType.Size() { return actualValue.Convert(expectedType).Interface() == expected } return expectedValue.Convert(actualType).Interface() == actual } // isNumericType returns true if the type is one of: // int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, // float32, float64, complex64, complex128 func isNumericType(t reflect.Type) bool { return t.Kind() >= reflect.Int && t.Kind() <= reflect.Complex128 } /* CallerInfo is necessary because the assert functions use the testing object internally, causing it to print the file:line of the assert method, rather than where the problem actually occurred in calling code.*/ // CallerInfo returns an array of strings containing the file and line number // of each stack frame leading from the current test to the assert call that // failed. func CallerInfo() []string { var pc uintptr var ok bool var file string var line int var name string callers := []string{} for i := 0; ; i++ { pc, file, line, ok = runtime.Caller(i) if !ok { // The breaks below failed to terminate the loop, and we ran off the // end of the call stack. break } // This is a huge edge case, but it will panic if this is the case, see #180 if file == "<autogenerated>" { break } f := runtime.FuncForPC(pc) if f == nil { break } name = f.Name() // testing.tRunner is the standard library function that calls // tests. Subtests are called directly by tRunner, without going through // the Test/Benchmark/Example function that contains the t.Run calls, so // with subtests we should break when we hit tRunner, without adding it // to the list of callers. if name == "testing.tRunner" { break } parts := strings.Split(file, "/") if len(parts) > 1 { filename := parts[len(parts)-1] dir := parts[len(parts)-2] if (dir != "assert" && dir != "mock" && dir != "require") || filename == "mock_test.go" { callers = append(callers, fmt.Sprintf("%s:%d", file, line)) } } // Drop the package segments := strings.Split(name, ".") name = segments[len(segments)-1] if isTest(name, "Test") || isTest(name, "Benchmark") || isTest(name, "Example") { break } } return callers } // Stolen from the `go test` tool. // isTest tells whether name looks like a test (or benchmark, according to prefix). // It is a Test (say) if there is a character after Test that is not a lower-case letter. // We don't want TesticularCancer. func isTest(name, prefix string) bool { if !strings.HasPrefix(name, prefix) { return false } if len(name) == len(prefix) { // "Test" is ok return true } r, _ := utf8.DecodeRuneInString(name[len(prefix):]) return !unicode.IsLower(r) } func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { if len(msgAndArgs) == 0 || msgAndArgs == nil { return "" } if len(msgAndArgs) == 1 { msg := msgAndArgs[0] if msgAsStr, ok := msg.(string); ok { return msgAsStr } return fmt.Sprintf("%+v", msg) } if len(msgAndArgs) > 1 { return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) } return "" } // Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). // The longestLabelLen parameter specifies the length of the longest label in the output (required because this is the // basis on which the alignment occurs). func indentMessageLines(message string, longestLabelLen int) string { outBuf := new(bytes.Buffer) for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { // no need to align first line because it starts at the correct location (after the label) if i != 0 { // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") } outBuf.WriteString(scanner.Text()) } return outBuf.String() } type failNower interface { FailNow() } // FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } Fail(t, failureMessage, msgAndArgs...) // We cannot extend TestingT with FailNow() and // maintain backwards compatibility, so we fallback // to panicking when FailNow is not available in // TestingT. // See issue #263 if t, ok := t.(failNower); ok { t.FailNow() } else { panic("test failed and t is missing `FailNow()`") } return false } // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } content := []labeledContent{ {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, {"Error", failureMessage}, } // Add test name if the Go version supports it if n, ok := t.(interface { Name() string }); ok { content = append(content, labeledContent{"Test", n.Name()}) } message := messageFromMsgAndArgs(msgAndArgs...) if len(message) > 0 { content = append(content, labeledContent{"Messages", message}) } t.Errorf("\n%s", ""+labeledOutput(content...)) return false } type labeledContent struct { label string content string } // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: // // \t{{label}}:{{align_spaces}}\t{{content}}\n // // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this // alignment is achieved, "\t{{content}}\n" is added for the output. // // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. func labeledOutput(content ...labeledContent) string { longestLabel := 0 for _, v := range content { if len(v.label) > longestLabel { longestLabel = len(v.label) } } var output string for _, v := range content { output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" } return output } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } interfaceType := reflect.TypeOf(interfaceObject).Elem() if object == nil { return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) } if !reflect.TypeOf(object).Implements(interfaceType) { return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) } return true } // NotImplements asserts that an object does not implement the specified interface. // // assert.NotImplements(t, (*MyInterface)(nil), new(MyObject)) func NotImplements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } interfaceType := reflect.TypeOf(interfaceObject).Elem() if object == nil { return Fail(t, fmt.Sprintf("Cannot check if nil does not implement %v", interfaceType), msgAndArgs...) } if reflect.TypeOf(object).Implements(interfaceType) { return Fail(t, fmt.Sprintf("%T implements %v", object, interfaceType), msgAndArgs...) } return true } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) } return true } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", expected, actual, err), msgAndArgs...) } if !ObjectsAreEqual(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true } // validateEqualArgs checks whether provided arguments can be safely used in the // Equal/NotEqual functions. func validateEqualArgs(expected, actual interface{}) error { if expected == nil && actual == nil { return nil } if isFunction(expected) || isFunction(actual) { return errors.New("cannot take func type as argument") } return nil } // Same asserts that two pointers reference the same object. // // assert.Same(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !samePointers(expected, actual) { return Fail(t, fmt.Sprintf("Not same: \n"+ "expected: %p %#v\n"+ "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...) } return true } // NotSame asserts that two pointers do not reference the same object. // // assert.NotSame(t, ptr1, ptr2) // // Both arguments must be pointer variables. Pointer variable sameness is // determined based on the equality of both type and value. func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if samePointers(expected, actual) { return Fail(t, fmt.Sprintf( "Expected and actual point to the same object: %p %#v", expected, expected), msgAndArgs...) } return true } // samePointers compares two generic interface objects and returns whether // they point to the same object func samePointers(first, second interface{}) bool { firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second) if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr { return false } firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second) if firstType != secondType { return false } // compare pointer addresses return first == second } // formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed // with the type name, and the value will be enclosed in parentheses similar // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)), fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual)) } switch expected.(type) { case time.Duration: return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual) } return truncatingFormat(expected), truncatingFormat(actual) } // truncatingFormat formats the data and truncates it if it's too long. // // This helps keep formatted error messages lines from exceeding the // bufio.MaxScanTokenSize max line length that the go testing framework imposes. func truncatingFormat(data interface{}) string { value := fmt.Sprintf("%#v", data) max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed. if len(value) > max { value = value[0:max] + "<... truncated>" } return value } // EqualValues asserts that two objects are equal or convertible to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !ObjectsAreEqualValues(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true } // EqualExportedValues asserts that the types of two objects are equal and their public // fields are also equal. This is useful for comparing structs that have private fields // that could potentially differ. // // type S struct { // Exported int // notExported int // } // assert.EqualExportedValues(t, S{1, 2}, S{1, 3}) => true // assert.EqualExportedValues(t, S{1, 2}, S{2, 3}) => false func EqualExportedValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } aType := reflect.TypeOf(expected) bType := reflect.TypeOf(actual) if aType != bType { return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) } if aType.Kind() == reflect.Ptr { aType = aType.Elem() } if bType.Kind() == reflect.Ptr { bType = bType.Elem() } if aType.Kind() != reflect.Struct { return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", aType.Kind(), reflect.Struct), msgAndArgs...) } if bType.Kind() != reflect.Struct { return Fail(t, fmt.Sprintf("Types expected to both be struct or pointer to struct \n\t%v != %v", bType.Kind(), reflect.Struct), msgAndArgs...) } expected = copyExportedFields(expected) actual = copyExportedFields(actual) if !ObjectsAreEqualValues(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal (comparing only exported fields): \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true } // Exactly asserts that two objects are equal in value and type. // // assert.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } aType := reflect.TypeOf(expected) bType := reflect.TypeOf(actual) if aType != bType { return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) } return Equal(t, expected, actual, msgAndArgs...) } // NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if !isNil(object) { return true } if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, "Expected value not to be nil.", msgAndArgs...) } // isNil checks if a specified object is nil or not, without Failing. func isNil(object interface{}) bool { if object == nil { return true } value := reflect.ValueOf(object) switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: return value.IsNil() } return false } // Nil asserts that the specified object is nil. // // assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if isNil(object) { return true } if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) } // isEmpty gets whether the specified object is considered empty or not. func isEmpty(object interface{}) bool { // get nil case out of the way if object == nil { return true } objValue := reflect.ValueOf(object) switch objValue.Kind() { // collection types are empty when they have no element case reflect.Chan, reflect.Map, reflect.Slice: return objValue.Len() == 0 // pointers are empty if nil or if the value they point to is empty case reflect.Ptr: if objValue.IsNil() { return true } deref := objValue.Elem().Interface() return isEmpty(deref) // for all other types, compare against the zero value // array types are empty when they match their zero-initialized state default: zero := reflect.Zero(objValue.Type()) return reflect.DeepEqual(object, zero.Interface()) } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { pass := isEmpty(object) if !pass { if h, ok := t.(tHelper); ok { h.Helper() } Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) } return pass } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmpty(t, obj) { // assert.Equal(t, "two", obj[1]) // } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { pass := !isEmpty(object) if !pass { if h, ok := t.(tHelper); ok { h.Helper() } Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) } return pass } // getLen tries to get the length of an object. // It returns (0, false) if impossible. func getLen(x interface{}) (length int, ok bool) { v := reflect.ValueOf(x) defer func() { ok = recover() == nil }() return v.Len(), true } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3) func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } l, ok := getLen(object) if !ok { return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...) } if l != length { return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) } return true } // True asserts that the specified value is true. // // assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { if !value { if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, "Should be true", msgAndArgs...) } return true } // False asserts that the specified value is false. // // assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { if value { if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, "Should be false", msgAndArgs...) } return true } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(t, obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", expected, actual, err), msgAndArgs...) } if ObjectsAreEqual(expected, actual) { return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) } return true } // NotEqualValues asserts that two objects are not equal even when converted to the same type // // assert.NotEqualValues(t, obj1, obj2) func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if ObjectsAreEqualValues(expected, actual) { return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) } return true } // containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. // return (true, true) if element was found. func containsElement(list interface{}, element interface{}) (ok, found bool) { listValue := reflect.ValueOf(list) listType := reflect.TypeOf(list) if listType == nil { return false, false } listKind := listType.Kind() defer func() { if e := recover(); e != nil { ok = false found = false } }() if listKind == reflect.String { elementValue := reflect.ValueOf(element) return true, strings.Contains(listValue.String(), elementValue.String()) } if listKind == reflect.Map { mapKeys := listValue.MapKeys() for i := 0; i < len(mapKeys); i++ { if ObjectsAreEqual(mapKeys[i].Interface(), element) { return true, true } } return true, false } for i := 0; i < listValue.Len(); i++ { if ObjectsAreEqual(listValue.Index(i).Interface(), element) { return true, true } } return true, false } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } ok, found := containsElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...) } return true } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth") // assert.NotContains(t, ["Hello", "World"], "Earth") // assert.NotContains(t, {"Hello": "World"}, "Earth") func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } ok, found := containsElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...) } if found { return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...) } return true } // Subset asserts that the specified list(array, slice...) or map contains all // elements given in the specified subset list(array, slice...) or map. // // assert.Subset(t, [1, 2, 3], [1, 2]) // assert.Subset(t, {"x": 1, "y": 2}, {"x": 1}) func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() } if subset == nil { return true // we consider nil to be equal to the nil set } listKind := reflect.TypeOf(list).Kind() if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } subsetKind := reflect.TypeOf(subset).Kind() if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } if subsetKind == reflect.Map && listKind == reflect.Map { subsetMap := reflect.ValueOf(subset) actualMap := reflect.ValueOf(list) for _, k := range subsetMap.MapKeys() { ev := subsetMap.MapIndex(k) av := actualMap.MapIndex(k) if !av.IsValid() { return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...) } if !ObjectsAreEqual(ev.Interface(), av.Interface()) { return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...) } } return true } subsetList := reflect.ValueOf(subset) for i := 0; i < subsetList.Len(); i++ { element := subsetList.Index(i).Interface() ok, found := containsElement(list, element) if !ok { return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...) } } return true } // NotSubset asserts that the specified list(array, slice...) or map does NOT // contain all elements given in the specified subset list(array, slice...) or // map. // // assert.NotSubset(t, [1, 3, 4], [1, 2]) // assert.NotSubset(t, {"x": 1, "y": 2}, {"z": 3}) func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() } if subset == nil { return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...) } listKind := reflect.TypeOf(list).Kind() if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } subsetKind := reflect.TypeOf(subset).Kind() if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } if subsetKind == reflect.Map && listKind == reflect.Map { subsetMap := reflect.ValueOf(subset) actualMap := reflect.ValueOf(list) for _, k := range subsetMap.MapKeys() { ev := subsetMap.MapIndex(k) av := actualMap.MapIndex(k) if !av.IsValid() { return true } if !ObjectsAreEqual(ev.Interface(), av.Interface()) { return true } } return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) } subsetList := reflect.ValueOf(subset) for i := 0; i < subsetList.Len(); i++ { element := subsetList.Index(i).Interface() ok, found := containsElement(list, element) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) } if !found { return true } } return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) } // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() } if isEmpty(listA) && isEmpty(listB) { return true } if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) { return false } extraA, extraB := diffLists(listA, listB) if len(extraA) == 0 && len(extraB) == 0 { return true } return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...) } // isList checks that the provided value is array or slice. func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) { kind := reflect.TypeOf(list).Kind()
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/doc.go
vendor/github.com/stretchr/testify/assert/doc.go
// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. // // # Example Usage // // The following is a complete example using assert in a standard test function: // // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(t, a, b, "The two words should be the same.") // // } // // if you assert many times, use the format below: // // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // assert := assert.New(t) // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(a, b, "The two words should be the same.") // } // // # Assertions // // Assertions allow you to easily write test code, and are global funcs in the `assert` package. // All assertion functions take, as the first argument, the `*testing.T` object provided by the // testing framework. This allows the assertion funcs to write the failings and other details to // the correct place. // // Every assertion function also takes an optional string message as the final argument, // allowing custom error messages to be appended to the message the assertion method outputs. package assert
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/assertion_order.go
vendor/github.com/stretchr/testify/assert/assertion_order.go
package assert import ( "fmt" "reflect" ) // isOrdered checks that collection contains orderable elements. func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { objKind := reflect.TypeOf(object).Kind() if objKind != reflect.Slice && objKind != reflect.Array { return false } objValue := reflect.ValueOf(object) objLen := objValue.Len() if objLen <= 1 { return true } value := objValue.Index(0) valueInterface := value.Interface() firstValueKind := value.Kind() for i := 1; i < objLen; i++ { prevValue := value prevValueInterface := valueInterface value = objValue.Index(i) valueInterface = value.Interface() compareResult, isComparable := compare(prevValueInterface, valueInterface, firstValueKind) if !isComparable { return Fail(t, fmt.Sprintf("Can not compare type \"%s\" and \"%s\"", reflect.TypeOf(value), reflect.TypeOf(prevValue)), msgAndArgs...) } if !containsValue(allowedComparesResults, compareResult) { return Fail(t, fmt.Sprintf(failMessage, prevValue, value), msgAndArgs...) } } return true } // IsIncreasing asserts that the collection is increasing // // assert.IsIncreasing(t, []int{1, 2, 3}) // assert.IsIncreasing(t, []float{1, 2}) // assert.IsIncreasing(t, []string{"a", "b"}) func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) } // IsNonIncreasing asserts that the collection is not increasing // // assert.IsNonIncreasing(t, []int{2, 1, 1}) // assert.IsNonIncreasing(t, []float{2, 1}) // assert.IsNonIncreasing(t, []string{"b", "a"}) func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) } // IsDecreasing asserts that the collection is decreasing // // assert.IsDecreasing(t, []int{2, 1, 0}) // assert.IsDecreasing(t, []float{2, 1}) // assert.IsDecreasing(t, []string{"b", "a"}) func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) } // IsNonDecreasing asserts that the collection is not decreasing // // assert.IsNonDecreasing(t, []int{1, 1, 2}) // assert.IsNonDecreasing(t, []float{1, 2}) // assert.IsNonDecreasing(t, []string{"a", "b"}) func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { return isOrdered(t, object, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/stretchr/testify/assert/http_assertions.go
vendor/github.com/stretchr/testify/assert/http_assertions.go
package assert import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" ) // httpCode is a helper that returns HTTP code of the response. It returns -1 and // an error if building a new request fails. func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { w := httptest.NewRecorder() req, err := http.NewRequest(method, url, http.NoBody) if err != nil { return -1, err } req.URL.RawQuery = values.Encode() handler(w, req) return w.Code, nil } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent if !isSuccessCode { Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isSuccessCode } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect if !isRedirectCode { Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isRedirectCode } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } isErrorCode := code >= http.StatusBadRequest if !isErrorCode { Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code), msgAndArgs...) } return isErrorCode } // HTTPStatusCode asserts that a specified handler returns a specified status code. // // assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) // // Returns whether the assertion was successful (true) or not (false). func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err), msgAndArgs...) } successful := code == statuscode if !successful { Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code), msgAndArgs...) } return successful } // HTTPBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() if len(values) > 0 { url += "?" + values.Encode() } req, err := http.NewRequest(method, url, http.NoBody) if err != nil { return "" } handler(w, req) return w.Body.String() } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } body := HTTPBody(handler, method, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if !contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body), msgAndArgs...) } return contains } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } body := HTTPBody(handler, method, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body), msgAndArgs...) } return !contains }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/join_unwrap_backward.go
vendor/github.com/go-errors/errors/join_unwrap_backward.go
//go:build !go1.20 // +build !go1.20 package errors // Disclaimer: functions Join and Unwrap are copied from the stdlib errors // package v1.21.0. // Join returns an error that wraps the given errors. // Any nil error values are discarded. // Join returns nil if every value in errs is nil. // The error formats as the concatenation of the strings obtained // by calling the Error method of each element of errs, with a newline // between each string. // // A non-nil error returned by Join implements the Unwrap() []error method. func Join(errs ...error) error { n := 0 for _, err := range errs { if err != nil { n++ } } if n == 0 { return nil } e := &joinError{ errs: make([]error, 0, n), } for _, err := range errs { if err != nil { e.errs = append(e.errs, err) } } return e } type joinError struct { errs []error } func (e *joinError) Error() string { var b []byte for i, err := range e.errs { if i > 0 { b = append(b, '\n') } b = append(b, err.Error()...) } return string(b) } func (e *joinError) Unwrap() []error { return e.errs } // Unwrap returns the result of calling the Unwrap method on err, if err's // type contains an Unwrap method returning error. // Otherwise, Unwrap returns nil. // // Unwrap only calls a method of the form "Unwrap() error". // In particular Unwrap does not unwrap errors returned by [Join]. func Unwrap(err error) error { u, ok := err.(interface { Unwrap() error }) if !ok { return nil } return u.Unwrap() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/error.go
vendor/github.com/go-errors/errors/error.go
// Package errors provides errors that have stack-traces. // // This is particularly useful when you want to understand the // state of execution when an error was returned unexpectedly. // // It provides the type *Error which implements the standard // golang error interface, so you can use this library interchangably // with code that is expecting a normal error return. // // For example: // // package crashy // // import "github.com/go-errors/errors" // // var Crashed = errors.Errorf("oh dear") // // func Crash() error { // return errors.New(Crashed) // } // // This can be called as follows: // // package main // // import ( // "crashy" // "fmt" // "github.com/go-errors/errors" // ) // // func main() { // err := crashy.Crash() // if err != nil { // if errors.Is(err, crashy.Crashed) { // fmt.Println(err.(*errors.Error).ErrorStack()) // } else { // panic(err) // } // } // } // // This package was original written to allow reporting to Bugsnag, // but after I found similar packages by Facebook and Dropbox, it // was moved to one canonical location so everyone can benefit. package errors import ( "bytes" "fmt" "reflect" "runtime" ) // The maximum number of stackframes on any error. var MaxStackDepth = 50 // Error is an error with an attached stacktrace. It can be used // wherever the builtin error interface is expected. type Error struct { Err error stack []uintptr frames []StackFrame prefix string } // New makes an Error from the given value. If that value is already an // error then it will be used directly, if not, it will be passed to // fmt.Errorf("%v"). The stacktrace will point to the line of code that // called New. func New(e interface{}) *Error { var err error switch e := e.(type) { case error: err = e default: err = fmt.Errorf("%v", e) } stack := make([]uintptr, MaxStackDepth) length := runtime.Callers(2, stack[:]) return &Error{ Err: err, stack: stack[:length], } } // Wrap makes an Error from the given value. If that value is already an // error then it will be used directly, if not, it will be passed to // fmt.Errorf("%v"). The skip parameter indicates how far up the stack // to start the stacktrace. 0 is from the current call, 1 from its caller, etc. func Wrap(e interface{}, skip int) *Error { if e == nil { return nil } var err error switch e := e.(type) { case *Error: return e case error: err = e default: err = fmt.Errorf("%v", e) } stack := make([]uintptr, MaxStackDepth) length := runtime.Callers(2+skip, stack[:]) return &Error{ Err: err, stack: stack[:length], } } // WrapPrefix makes an Error from the given value. If that value is already an // error then it will be used directly, if not, it will be passed to // fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the // error message when calling Error(). The skip parameter indicates how far // up the stack to start the stacktrace. 0 is from the current call, // 1 from its caller, etc. func WrapPrefix(e interface{}, prefix string, skip int) *Error { if e == nil { return nil } err := Wrap(e, 1+skip) if err.prefix != "" { prefix = fmt.Sprintf("%s: %s", prefix, err.prefix) } return &Error{ Err: err.Err, stack: err.stack, prefix: prefix, } } // Errorf creates a new error with the given message. You can use it // as a drop-in replacement for fmt.Errorf() to provide descriptive // errors in return values. func Errorf(format string, a ...interface{}) *Error { return Wrap(fmt.Errorf(format, a...), 1) } // Error returns the underlying error's message. func (err *Error) Error() string { msg := err.Err.Error() if err.prefix != "" { msg = fmt.Sprintf("%s: %s", err.prefix, msg) } return msg } // Stack returns the callstack formatted the same way that go does // in runtime/debug.Stack() func (err *Error) Stack() []byte { buf := bytes.Buffer{} for _, frame := range err.StackFrames() { buf.WriteString(frame.String()) } return buf.Bytes() } // Callers satisfies the bugsnag ErrorWithCallerS() interface // so that the stack can be read out. func (err *Error) Callers() []uintptr { return err.stack } // ErrorStack returns a string that contains both the // error message and the callstack. func (err *Error) ErrorStack() string { return err.TypeName() + " " + err.Error() + "\n" + string(err.Stack()) } // StackFrames returns an array of frames containing information about the // stack. func (err *Error) StackFrames() []StackFrame { if err.frames == nil { err.frames = make([]StackFrame, len(err.stack)) for i, pc := range err.stack { err.frames[i] = NewStackFrame(pc) } } return err.frames } // TypeName returns the type this error. e.g. *errors.stringError. func (err *Error) TypeName() string { if _, ok := err.Err.(uncaughtPanic); ok { return "panic" } return reflect.TypeOf(err.Err).String() } // Return the wrapped error (implements api for As function). func (err *Error) Unwrap() error { return err.Err }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/error_backward.go
vendor/github.com/go-errors/errors/error_backward.go
//go:build !go1.13 // +build !go1.13 package errors import ( "reflect" ) type unwrapper interface { Unwrap() error } // As assigns error or any wrapped error to the value target points // to. If there is no value of the target type of target As returns // false. func As(err error, target interface{}) bool { targetType := reflect.TypeOf(target) for { errType := reflect.TypeOf(err) if errType == nil { return false } if reflect.PtrTo(errType) == targetType { reflect.ValueOf(target).Elem().Set(reflect.ValueOf(err)) return true } wrapped, ok := err.(unwrapper) if ok { err = wrapped.Unwrap() } else { return false } } } // Is detects whether the error is equal to a given error. Errors // are considered equal by this function if they are the same object, // or if they both contain the same error inside an errors.Error. func Is(e error, original error) bool { if e == original { return true } if e, ok := e.(*Error); ok { return Is(e.Err, original) } if original, ok := original.(*Error); ok { return Is(e, original.Err) } return false } // Disclaimer: functions Join and Unwrap are copied from the stdlib errors // package v1.21.0. // Join returns an error that wraps the given errors. // Any nil error values are discarded. // Join returns nil if every value in errs is nil. // The error formats as the concatenation of the strings obtained // by calling the Error method of each element of errs, with a newline // between each string. // // A non-nil error returned by Join implements the Unwrap() []error method. func Join(errs ...error) error { n := 0 for _, err := range errs { if err != nil { n++ } } if n == 0 { return nil } e := &joinError{ errs: make([]error, 0, n), } for _, err := range errs { if err != nil { e.errs = append(e.errs, err) } } return e } type joinError struct { errs []error } func (e *joinError) Error() string { var b []byte for i, err := range e.errs { if i > 0 { b = append(b, '\n') } b = append(b, err.Error()...) } return string(b) } func (e *joinError) Unwrap() []error { return e.errs } // Unwrap returns the result of calling the Unwrap method on err, if err's // type contains an Unwrap method returning error. // Otherwise, Unwrap returns nil. // // Unwrap only calls a method of the form "Unwrap() error". // In particular Unwrap does not unwrap errors returned by [Join]. func Unwrap(err error) error { u, ok := err.(interface { Unwrap() error }) if !ok { return nil } return u.Unwrap() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/parse_panic.go
vendor/github.com/go-errors/errors/parse_panic.go
package errors import ( "strconv" "strings" ) type uncaughtPanic struct{ message string } func (p uncaughtPanic) Error() string { return p.message } // ParsePanic allows you to get an error object from the output of a go program // that panicked. This is particularly useful with https://github.com/mitchellh/panicwrap. func ParsePanic(text string) (*Error, error) { lines := strings.Split(text, "\n") state := "start" var message string var stack []StackFrame for i := 0; i < len(lines); i++ { line := lines[i] if state == "start" { if strings.HasPrefix(line, "panic: ") { message = strings.TrimPrefix(line, "panic: ") state = "seek" } else { return nil, Errorf("bugsnag.panicParser: Invalid line (no prefix): %s", line) } } else if state == "seek" { if strings.HasPrefix(line, "goroutine ") && strings.HasSuffix(line, "[running]:") { state = "parsing" } } else if state == "parsing" { if line == "" { state = "done" break } createdBy := false if strings.HasPrefix(line, "created by ") { line = strings.TrimPrefix(line, "created by ") createdBy = true } i++ if i >= len(lines) { return nil, Errorf("bugsnag.panicParser: Invalid line (unpaired): %s", line) } frame, err := parsePanicFrame(line, lines[i], createdBy) if err != nil { return nil, err } stack = append(stack, *frame) if createdBy { state = "done" break } } } if state == "done" || state == "parsing" { return &Error{Err: uncaughtPanic{message}, frames: stack}, nil } return nil, Errorf("could not parse panic: %v", text) } // The lines we're passing look like this: // // main.(*foo).destruct(0xc208067e98) // /0/go/src/github.com/bugsnag/bugsnag-go/pan/main.go:22 +0x151 func parsePanicFrame(name string, line string, createdBy bool) (*StackFrame, error) { idx := strings.LastIndex(name, "(") if idx == -1 && !createdBy { return nil, Errorf("bugsnag.panicParser: Invalid line (no call): %s", name) } if idx != -1 { name = name[:idx] } pkg := "" if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { pkg += name[:lastslash] + "/" name = name[lastslash+1:] } if period := strings.Index(name, "."); period >= 0 { pkg += name[:period] name = name[period+1:] } name = strings.Replace(name, "·", ".", -1) if !strings.HasPrefix(line, "\t") { return nil, Errorf("bugsnag.panicParser: Invalid line (no tab): %s", line) } idx = strings.LastIndex(line, ":") if idx == -1 { return nil, Errorf("bugsnag.panicParser: Invalid line (no line number): %s", line) } file := line[1:idx] number := line[idx+1:] if idx = strings.Index(number, " +"); idx > -1 { number = number[:idx] } lno, err := strconv.ParseInt(number, 10, 32) if err != nil { return nil, Errorf("bugsnag.panicParser: Invalid line (bad line number): %s", line) } return &StackFrame{ File: file, LineNumber: int(lno), Package: pkg, Name: name, }, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/stackframe.go
vendor/github.com/go-errors/errors/stackframe.go
package errors import ( "bufio" "bytes" "fmt" "os" "runtime" "strings" ) // A StackFrame contains all necessary information about to generate a line // in a callstack. type StackFrame struct { // The path to the file containing this ProgramCounter File string // The LineNumber in that file LineNumber int // The Name of the function that contains this ProgramCounter Name string // The Package that contains this function Package string // The underlying ProgramCounter ProgramCounter uintptr } // NewStackFrame popoulates a stack frame object from the program counter. func NewStackFrame(pc uintptr) (frame StackFrame) { frame = StackFrame{ProgramCounter: pc} if frame.Func() == nil { return } frame.Package, frame.Name = packageAndName(frame.Func()) // pc -1 because the program counters we use are usually return addresses, // and we want to show the line that corresponds to the function call frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1) return } // Func returns the function that contained this frame. func (frame *StackFrame) Func() *runtime.Func { if frame.ProgramCounter == 0 { return nil } return runtime.FuncForPC(frame.ProgramCounter) } // String returns the stackframe formatted in the same way as go does // in runtime/debug.Stack() func (frame *StackFrame) String() string { str := fmt.Sprintf("%s:%d (0x%x)\n", frame.File, frame.LineNumber, frame.ProgramCounter) source, err := frame.sourceLine() if err != nil { return str } return str + fmt.Sprintf("\t%s: %s\n", frame.Name, source) } // SourceLine gets the line of code (from File and Line) of the original source if possible. func (frame *StackFrame) SourceLine() (string, error) { source, err := frame.sourceLine() if err != nil { return source, New(err) } return source, err } func (frame *StackFrame) sourceLine() (string, error) { if frame.LineNumber <= 0 { return "???", nil } file, err := os.Open(frame.File) if err != nil { return "", err } defer file.Close() scanner := bufio.NewScanner(file) currentLine := 1 for scanner.Scan() { if currentLine == frame.LineNumber { return string(bytes.Trim(scanner.Bytes(), " \t")), nil } currentLine++ } if err := scanner.Err(); err != nil { return "", err } return "???", nil } func packageAndName(fn *runtime.Func) (string, string) { name := fn.Name() pkg := "" // The name includes the path name to the package, which is unnecessary // since the file name is already included. Plus, it has center dots. // That is, we see // runtime/debug.*T·ptrmethod // and want // *T.ptrmethod // Since the package path might contains dots (e.g. code.google.com/...), // we first remove the path prefix if there is one. if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { pkg += name[:lastslash] + "/" name = name[lastslash+1:] } if period := strings.Index(name, "."); period >= 0 { pkg += name[:period] name = name[period+1:] } name = strings.Replace(name, "·", ".", -1) return pkg, name }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/error_1_13.go
vendor/github.com/go-errors/errors/error_1_13.go
//go:build go1.13 // +build go1.13 package errors import ( baseErrors "errors" ) // As finds the first error in err's tree that matches target, and if one is found, sets // target to that error value and returns true. Otherwise, it returns false. // // For more information see stdlib errors.As. func As(err error, target interface{}) bool { return baseErrors.As(err, target) } // Is detects whether the error is equal to a given error. Errors // are considered equal by this function if they are matched by errors.Is // or if their contained errors are matched through errors.Is. func Is(e error, original error) bool { if baseErrors.Is(e, original) { return true } if e, ok := e.(*Error); ok { return Is(e.Err, original) } if original, ok := original.(*Error); ok { return Is(e, original.Err) } return false }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/go-errors/errors/join_unwrap_1_20.go
vendor/github.com/go-errors/errors/join_unwrap_1_20.go
//go:build go1.20 // +build go1.20 package errors import baseErrors "errors" // Join returns an error that wraps the given errors. // Any nil error values are discarded. // Join returns nil if every value in errs is nil. // The error formats as the concatenation of the strings obtained // by calling the Error method of each element of errs, with a newline // between each string. // // A non-nil error returned by Join implements the Unwrap() []error method. // // For more information see stdlib errors.Join. func Join(errs ...error) error { return baseErrors.Join(errs...) } // Unwrap returns the result of calling the Unwrap method on err, if err's // type contains an Unwrap method returning error. // Otherwise, Unwrap returns nil. // // Unwrap only calls a method of the form "Unwrap() error". // In particular Unwrap does not unwrap errors returned by [Join]. // // For more information see stdlib errors.Unwrap. func Unwrap(err error) error { return baseErrors.Unwrap(err) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/pkg/errors/errors.go
vendor/github.com/pkg/errors/errors.go
// Package errors provides simple error handling primitives. // // The traditional error handling idiom in Go is roughly akin to // // if err != nil { // return err // } // // which when applied recursively up the call stack results in error reports // without context or debugging information. The errors package allows // programmers to add context to the failure path in their code in a way // that does not destroy the original value of the error. // // Adding context to an error // // The errors.Wrap function returns a new error that adds context to the // original error by recording a stack trace at the point Wrap is called, // together with the supplied message. For example // // _, err := ioutil.ReadAll(r) // if err != nil { // return errors.Wrap(err, "read failed") // } // // If additional control is required, the errors.WithStack and // errors.WithMessage functions destructure errors.Wrap into its component // operations: annotating an error with a stack trace and with a message, // respectively. // // Retrieving the cause of an error // // Using errors.Wrap constructs a stack of errors, adding context to the // preceding error. Depending on the nature of the error it may be necessary // to reverse the operation of errors.Wrap to retrieve the original error // for inspection. Any error value which implements this interface // // type causer interface { // Cause() error // } // // can be inspected by errors.Cause. errors.Cause will recursively retrieve // the topmost error that does not implement causer, which is assumed to be // the original cause. For example: // // switch err := errors.Cause(err).(type) { // case *MyError: // // handle specifically // default: // // unknown error // } // // Although the causer interface is not exported by this package, it is // considered a part of its stable public interface. // // Formatted printing of errors // // All error values returned from this package implement fmt.Formatter and can // be formatted by the fmt package. The following verbs are supported: // // %s print the error. If the error has a Cause it will be // printed recursively. // %v see %s // %+v extended format. Each Frame of the error's StackTrace will // be printed in detail. // // Retrieving the stack trace of an error or wrapper // // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are // invoked. This information can be retrieved with the following interface: // // type stackTracer interface { // StackTrace() errors.StackTrace // } // // The returned errors.StackTrace type is defined as // // type StackTrace []Frame // // The Frame type represents a call site in the stack trace. Frame supports // the fmt.Formatter interface that can be used for printing information about // the stack trace of this error. For example: // // if err, ok := err.(stackTracer); ok { // for _, f := range err.StackTrace() { // fmt.Printf("%+s:%d\n", f, f) // } // } // // Although the stackTracer interface is not exported by this package, it is // considered a part of its stable public interface. // // See the documentation for Frame.Format for more details. package errors import ( "fmt" "io" ) // New returns an error with the supplied message. // New also records the stack trace at the point it was called. func New(message string) error { return &fundamental{ msg: message, stack: callers(), } } // Errorf formats according to a format specifier and returns the string // as a value that satisfies error. // Errorf also records the stack trace at the point it was called. func Errorf(format string, args ...interface{}) error { return &fundamental{ msg: fmt.Sprintf(format, args...), stack: callers(), } } // fundamental is an error that has a message and a stack, but no caller. type fundamental struct { msg string *stack } func (f *fundamental) Error() string { return f.msg } func (f *fundamental) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { io.WriteString(s, f.msg) f.stack.Format(s, verb) return } fallthrough case 's': io.WriteString(s, f.msg) case 'q': fmt.Fprintf(s, "%q", f.msg) } } // WithStack annotates err with a stack trace at the point WithStack was called. // If err is nil, WithStack returns nil. func WithStack(err error) error { if err == nil { return nil } return &withStack{ err, callers(), } } type withStack struct { error *stack } func (w *withStack) Cause() error { return w.error } // Unwrap provides compatibility for Go 1.13 error chains. func (w *withStack) Unwrap() error { return w.error } func (w *withStack) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { fmt.Fprintf(s, "%+v", w.Cause()) w.stack.Format(s, verb) return } fallthrough case 's': io.WriteString(s, w.Error()) case 'q': fmt.Fprintf(s, "%q", w.Error()) } } // Wrap returns an error annotating err with a stack trace // at the point Wrap is called, and the supplied message. // If err is nil, Wrap returns nil. func Wrap(err error, message string) error { if err == nil { return nil } err = &withMessage{ cause: err, msg: message, } return &withStack{ err, callers(), } } // Wrapf returns an error annotating err with a stack trace // at the point Wrapf is called, and the format specifier. // If err is nil, Wrapf returns nil. func Wrapf(err error, format string, args ...interface{}) error { if err == nil { return nil } err = &withMessage{ cause: err, msg: fmt.Sprintf(format, args...), } return &withStack{ err, callers(), } } // WithMessage annotates err with a new message. // If err is nil, WithMessage returns nil. func WithMessage(err error, message string) error { if err == nil { return nil } return &withMessage{ cause: err, msg: message, } } // WithMessagef annotates err with the format specifier. // If err is nil, WithMessagef returns nil. func WithMessagef(err error, format string, args ...interface{}) error { if err == nil { return nil } return &withMessage{ cause: err, msg: fmt.Sprintf(format, args...), } } type withMessage struct { cause error msg string } func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } func (w *withMessage) Cause() error { return w.cause } // Unwrap provides compatibility for Go 1.13 error chains. func (w *withMessage) Unwrap() error { return w.cause } func (w *withMessage) Format(s fmt.State, verb rune) { switch verb { case 'v': if s.Flag('+') { fmt.Fprintf(s, "%+v\n", w.Cause()) io.WriteString(s, w.msg) return } fallthrough case 's', 'q': io.WriteString(s, w.Error()) } } // Cause returns the underlying cause of the error, if possible. // An error value has a cause if it implements the following // interface: // // type causer interface { // Cause() error // } // // If the error does not implement Cause, the original error will // be returned. If the error is nil, nil will be returned without further // investigation. func Cause(err error) error { type causer interface { Cause() error } for err != nil { cause, ok := err.(causer) if !ok { break } err = cause.Cause() } return err }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/pkg/errors/go113.go
vendor/github.com/pkg/errors/go113.go
// +build go1.13 package errors import ( stderrors "errors" ) // Is reports whether any error in err's chain matches target. // // The chain consists of err itself followed by the sequence of errors obtained by // repeatedly calling Unwrap. // // An error is considered to match a target if it is equal to that target or if // it implements a method Is(error) bool such that Is(target) returns true. func Is(err, target error) bool { return stderrors.Is(err, target) } // As finds the first error in err's chain that matches target, and if so, sets // target to that error value and returns true. // // The chain consists of err itself followed by the sequence of errors obtained by // repeatedly calling Unwrap. // // An error matches target if the error's concrete value is assignable to the value // pointed to by target, or if the error has a method As(interface{}) bool such that // As(target) returns true. In the latter case, the As method is responsible for // setting target. // // As will panic if target is not a non-nil pointer to either a type that implements // error, or to any interface type. As returns false if err is nil. func As(err error, target interface{}) bool { return stderrors.As(err, target) } // Unwrap returns the result of calling the Unwrap method on err, if err's // type contains an Unwrap method returning error. // Otherwise, Unwrap returns nil. func Unwrap(err error) error { return stderrors.Unwrap(err) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/pkg/errors/stack.go
vendor/github.com/pkg/errors/stack.go
package errors import ( "fmt" "io" "path" "runtime" "strconv" "strings" ) // Frame represents a program counter inside a stack frame. // For historical reasons if Frame is interpreted as a uintptr // its value represents the program counter + 1. type Frame uintptr // pc returns the program counter for this frame; // multiple frames may have the same PC value. func (f Frame) pc() uintptr { return uintptr(f) - 1 } // file returns the full path to the file that contains the // function for this Frame's pc. func (f Frame) file() string { fn := runtime.FuncForPC(f.pc()) if fn == nil { return "unknown" } file, _ := fn.FileLine(f.pc()) return file } // line returns the line number of source code of the // function for this Frame's pc. func (f Frame) line() int { fn := runtime.FuncForPC(f.pc()) if fn == nil { return 0 } _, line := fn.FileLine(f.pc()) return line } // name returns the name of this function, if known. func (f Frame) name() string { fn := runtime.FuncForPC(f.pc()) if fn == nil { return "unknown" } return fn.Name() } // Format formats the frame according to the fmt.Formatter interface. // // %s source file // %d source line // %n function name // %v equivalent to %s:%d // // Format accepts flags that alter the printing of some verbs, as follows: // // %+s function name and path of source file relative to the compile time // GOPATH separated by \n\t (<funcname>\n\t<path>) // %+v equivalent to %+s:%d func (f Frame) Format(s fmt.State, verb rune) { switch verb { case 's': switch { case s.Flag('+'): io.WriteString(s, f.name()) io.WriteString(s, "\n\t") io.WriteString(s, f.file()) default: io.WriteString(s, path.Base(f.file())) } case 'd': io.WriteString(s, strconv.Itoa(f.line())) case 'n': io.WriteString(s, funcname(f.name())) case 'v': f.Format(s, 's') io.WriteString(s, ":") f.Format(s, 'd') } } // MarshalText formats a stacktrace Frame as a text string. The output is the // same as that of fmt.Sprintf("%+v", f), but without newlines or tabs. func (f Frame) MarshalText() ([]byte, error) { name := f.name() if name == "unknown" { return []byte(name), nil } return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil } // StackTrace is stack of Frames from innermost (newest) to outermost (oldest). type StackTrace []Frame // Format formats the stack of Frames according to the fmt.Formatter interface. // // %s lists source files for each Frame in the stack // %v lists the source file and line number for each Frame in the stack // // Format accepts flags that alter the printing of some verbs, as follows: // // %+v Prints filename, function, and line number for each Frame in the stack. func (st StackTrace) Format(s fmt.State, verb rune) { switch verb { case 'v': switch { case s.Flag('+'): for _, f := range st { io.WriteString(s, "\n") f.Format(s, verb) } case s.Flag('#'): fmt.Fprintf(s, "%#v", []Frame(st)) default: st.formatSlice(s, verb) } case 's': st.formatSlice(s, verb) } } // formatSlice will format this StackTrace into the given buffer as a slice of // Frame, only valid when called with '%s' or '%v'. func (st StackTrace) formatSlice(s fmt.State, verb rune) { io.WriteString(s, "[") for i, f := range st { if i > 0 { io.WriteString(s, " ") } f.Format(s, verb) } io.WriteString(s, "]") } // stack represents a stack of program counters. type stack []uintptr func (s *stack) Format(st fmt.State, verb rune) { switch verb { case 'v': switch { case st.Flag('+'): for _, pc := range *s { f := Frame(pc) fmt.Fprintf(st, "\n%+v", f) } } } } func (s *stack) StackTrace() StackTrace { f := make([]Frame, len(*s)) for i := 0; i < len(f); i++ { f[i] = Frame((*s)[i]) } return f } func callers() *stack { const depth = 32 var pcs [depth]uintptr n := runtime.Callers(3, pcs[:]) var st stack = pcs[0:n] return &st } // funcname removes the path prefix component of a function's name reported by func.Name(). func funcname(name string) string { i := strings.LastIndex(name, "/") name = name[i+1:] i = strings.Index(name, ".") return name[i+1:] }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid_gccgo.go
vendor/github.com/petermattis/goid/goid_gccgo.go
// Copyright 2018 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build gccgo package goid //extern runtime.getg func getg() *g func Get() int64 { return getg().goid }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid.go
vendor/github.com/petermattis/goid/goid.go
// Copyright 2016 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. package goid import ( "bytes" "runtime" "strconv" ) func ExtractGID(s []byte) int64 { s = s[len("goroutine "):] s = s[:bytes.IndexByte(s, ' ')] gid, _ := strconv.ParseInt(string(s), 10, 64) return gid } // Parse the goid from runtime.Stack() output. Slow, but it works. func getSlow() int64 { var buf [64]byte return ExtractGID(buf[:runtime.Stack(buf[:], false)]) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid_slow.go
vendor/github.com/petermattis/goid/goid_slow.go
// Copyright 2016 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build go1.4,!go1.5,!amd64,!amd64p32,!arm,!386 go1.5,!go1.6,!amd64,!amd64p32,!arm go1.6,!amd64,!amd64p32,!arm go1.9,!amd64,!amd64p32,!arm package goid // Get returns the id of the current goroutine. func Get() int64 { return getSlow() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/runtime_go1.5.go
vendor/github.com/petermattis/goid/runtime_go1.5.go
// Copyright 2016 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build go1.5,!go1.6 package goid // Just enough of the structs from runtime/runtime2.go to get the offset to goid. // See https://github.com/golang/go/blob/release-branch.go1.5/src/runtime/runtime2.go type stack struct { lo uintptr hi uintptr } type gobuf struct { sp uintptr pc uintptr g uintptr ctxt uintptr ret uintptr lr uintptr bp uintptr } type g struct { stack stack stackguard0 uintptr stackguard1 uintptr _panic uintptr _defer uintptr m uintptr stackAlloc uintptr sched gobuf syscallsp uintptr syscallpc uintptr stkbar []uintptr stkbarPos uintptr param uintptr atomicstatus uint32 stackLock uint32 goid int64 // Here it is! }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid_go1.3.go
vendor/github.com/petermattis/goid/goid_go1.3.go
// Copyright 2015 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build !go1.4 package goid // Get returns the id of the current goroutine. func Get() int64
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/runtime_gccgo_go1.8.go
vendor/github.com/petermattis/goid/runtime_gccgo_go1.8.go
// +build gccgo,go1.8 package goid // https://github.com/gcc-mirror/gcc/blob/gcc-7-branch/libgo/go/runtime/runtime2.go#L329-L422 type g struct { _panic uintptr _defer uintptr m uintptr syscallsp uintptr syscallpc uintptr param uintptr atomicstatus uint32 goid int64 // Here it is! }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/runtime_go1.6.go
vendor/github.com/petermattis/goid/runtime_go1.6.go
// +build gc,go1.6,!go1.9 package goid // Just enough of the structs from runtime/runtime2.go to get the offset to goid. // See https://github.com/golang/go/blob/release-branch.go1.6/src/runtime/runtime2.go type stack struct { lo uintptr hi uintptr } type gobuf struct { sp uintptr pc uintptr g uintptr ctxt uintptr ret uintptr lr uintptr bp uintptr } type g struct { stack stack stackguard0 uintptr stackguard1 uintptr _panic uintptr _defer uintptr m uintptr stackAlloc uintptr sched gobuf syscallsp uintptr syscallpc uintptr stkbar []uintptr stkbarPos uintptr stktopsp uintptr param uintptr atomicstatus uint32 stackLock uint32 goid int64 // Here it is! }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/runtime_go1.9.go
vendor/github.com/petermattis/goid/runtime_go1.9.go
// +build gc,go1.9 package goid type stack struct { lo uintptr hi uintptr } type gobuf struct { sp uintptr pc uintptr g uintptr ctxt uintptr ret uintptr lr uintptr bp uintptr } type g struct { stack stack stackguard0 uintptr stackguard1 uintptr _panic uintptr _defer uintptr m uintptr sched gobuf syscallsp uintptr syscallpc uintptr stktopsp uintptr param uintptr atomicstatus uint32 stackLock uint32 goid int64 // Here it is! }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid_go1.4.go
vendor/github.com/petermattis/goid/goid_go1.4.go
// Copyright 2015 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build go1.4,!go1.5 package goid import "unsafe" var pointerSize = unsafe.Sizeof(uintptr(0)) // Backdoor access to runtime·getg(). func getg() uintptr // in goid_go1.4.s // Get returns the id of the current goroutine. func Get() int64 { // The goid is the 16th field in the G struct where each field is a // pointer, uintptr or padded to that size. See runtime.h from the // Go sources. I'm not aware of a cleaner way to determine the // offset. return *(*int64)(unsafe.Pointer(getg() + 16*pointerSize)) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid_go1.5_amd64.go
vendor/github.com/petermattis/goid/goid_go1.5_amd64.go
// Copyright 2016 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build amd64 amd64p32 // +build gc,go1.5 package goid func Get() int64
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/petermattis/goid/goid_go1.5_arm.go
vendor/github.com/petermattis/goid/goid_go1.5_arm.go
// Copyright 2016 Peter Mattis. // // 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. See the AUTHORS file // for names of contributors. // +build arm // +build gc,go1.5 package goid // Backdoor access to runtime·getg(). func getg() *g // in goid_go1.5plus.s func Get() int64 { return getg().goid }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/imdario/mergo/merge.go
vendor/github.com/imdario/mergo/merge.go
// Copyright 2013 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Based on src/pkg/reflect/deepequal.go from official // golang's stdlib. package mergo import ( "fmt" "reflect" ) func hasMergeableFields(dst reflect.Value) (exported bool) { for i, n := 0, dst.NumField(); i < n; i++ { field := dst.Type().Field(i) if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { exported = exported || hasMergeableFields(dst.Field(i)) } else if isExportedComponent(&field) { exported = exported || len(field.PkgPath) == 0 } } return } func isExportedComponent(field *reflect.StructField) bool { pkgPath := field.PkgPath if len(pkgPath) > 0 { return false } c := field.Name[0] if 'a' <= c && c <= 'z' || c == '_' { return false } return true } type Config struct { Transformers Transformers Overwrite bool ShouldNotDereference bool AppendSlice bool TypeCheck bool overwriteWithEmptyValue bool overwriteSliceWithEmptyValue bool sliceDeepCopy bool debug bool } type Transformers interface { Transformer(reflect.Type) func(dst, src reflect.Value) error } // Traverses recursively both values, assigning src's fields values to dst. // The map argument tracks comparisons that have already been seen, which allows // short circuiting on recursive types. func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { overwrite := config.Overwrite typeCheck := config.TypeCheck overwriteWithEmptySrc := config.overwriteWithEmptyValue overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue sliceDeepCopy := config.sliceDeepCopy if !src.IsValid() { return } if dst.CanAddr() { addr := dst.UnsafeAddr() h := 17 * addr seen := visited[h] typ := dst.Type() for p := seen; p != nil; p = p.next { if p.ptr == addr && p.typ == typ { return nil } } // Remember, remember... visited[h] = &visit{typ, seen, addr} } if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() { if fn := config.Transformers.Transformer(dst.Type()); fn != nil { err = fn(dst, src) return } } switch dst.Kind() { case reflect.Struct: if hasMergeableFields(dst) { for i, n := 0, dst.NumField(); i < n; i++ { if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { return } } } else { if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) { dst.Set(src) } } case reflect.Map: if dst.IsNil() && !src.IsNil() { if dst.CanSet() { dst.Set(reflect.MakeMap(dst.Type())) } else { dst = src return } } if src.Kind() != reflect.Map { if overwrite && dst.CanSet() { dst.Set(src) } return } for _, key := range src.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { continue } dstElement := dst.MapIndex(key) switch srcElement.Kind() { case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: if srcElement.IsNil() { if overwrite { dst.SetMapIndex(key, srcElement) } continue } fallthrough default: if !srcElement.CanInterface() { continue } switch reflect.TypeOf(srcElement.Interface()).Kind() { case reflect.Struct: fallthrough case reflect.Ptr: fallthrough case reflect.Map: srcMapElm := srcElement dstMapElm := dstElement if srcMapElm.CanInterface() { srcMapElm = reflect.ValueOf(srcMapElm.Interface()) if dstMapElm.IsValid() { dstMapElm = reflect.ValueOf(dstMapElm.Interface()) } } if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil { return } case reflect.Slice: srcSlice := reflect.ValueOf(srcElement.Interface()) var dstSlice reflect.Value if !dstElement.IsValid() || dstElement.IsNil() { dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len()) } else { dstSlice = reflect.ValueOf(dstElement.Interface()) } if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { if typeCheck && srcSlice.Type() != dstSlice.Type() { return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) } dstSlice = srcSlice } else if config.AppendSlice { if srcSlice.Type() != dstSlice.Type() { return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type()) } dstSlice = reflect.AppendSlice(dstSlice, srcSlice) } else if sliceDeepCopy { i := 0 for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ { srcElement := srcSlice.Index(i) dstElement := dstSlice.Index(i) if srcElement.CanInterface() { srcElement = reflect.ValueOf(srcElement.Interface()) } if dstElement.CanInterface() { dstElement = reflect.ValueOf(dstElement.Interface()) } if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } } dst.SetMapIndex(key, dstSlice) } } if dstElement.IsValid() && !isEmptyValue(dstElement, !config.ShouldNotDereference) { if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice { continue } if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map { continue } } if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) { if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } dst.SetMapIndex(key, srcElement) } } // Ensure that all keys in dst are deleted if they are not in src. if overwriteWithEmptySrc { for _, key := range dst.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { dst.SetMapIndex(key, reflect.Value{}) } } } case reflect.Slice: if !dst.CanSet() { break } if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy { dst.Set(src) } else if config.AppendSlice { if src.Type() != dst.Type() { return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) } dst.Set(reflect.AppendSlice(dst, src)) } else if sliceDeepCopy { for i := 0; i < src.Len() && i < dst.Len(); i++ { srcElement := src.Index(i) dstElement := dst.Index(i) if srcElement.CanInterface() { srcElement = reflect.ValueOf(srcElement.Interface()) } if dstElement.CanInterface() { dstElement = reflect.ValueOf(dstElement.Interface()) } if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } } case reflect.Ptr: fallthrough case reflect.Interface: if isReflectNil(src) { if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) { dst.Set(src) } break } if src.Kind() != reflect.Interface { if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { dst.Set(src) } } else if src.Kind() == reflect.Ptr { if !config.ShouldNotDereference { if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } } else { if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() { dst.Set(src) } } } else if dst.Elem().Type() == src.Type() { if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { return } } else { return ErrDifferentArgumentsTypes } break } if dst.IsNil() || overwrite { if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) { dst.Set(src) } break } if dst.Elem().Kind() == src.Elem().Kind() { if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } break } default: mustSet := (isEmptyValue(dst, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) if mustSet { if dst.CanSet() { dst.Set(src) } else { dst = src } } } return } // Merge will fill any empty for value type attributes on the dst struct using corresponding // src attributes if they themselves are not empty. dst and src must be valid same-type structs // and dst must be a pointer to struct. // It won't merge unexported (private) fields and will do recursively any exported field. func Merge(dst, src interface{}, opts ...func(*Config)) error { return merge(dst, src, opts...) } // MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by // non-empty src attribute values. // Deprecated: use Merge(…) with WithOverride func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { return merge(dst, src, append(opts, WithOverride)...) } // WithTransformers adds transformers to merge, allowing to customize the merging of some types. func WithTransformers(transformers Transformers) func(*Config) { return func(config *Config) { config.Transformers = transformers } } // WithOverride will make merge override non-empty dst attributes with non-empty src attributes values. func WithOverride(config *Config) { config.Overwrite = true } // WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. func WithOverwriteWithEmptyValue(config *Config) { config.Overwrite = true config.overwriteWithEmptyValue = true } // WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. func WithOverrideEmptySlice(config *Config) { config.overwriteSliceWithEmptyValue = true } // WithoutDereference prevents dereferencing pointers when evaluating whether they are empty // (i.e. a non-nil pointer is never considered empty). func WithoutDereference(config *Config) { config.ShouldNotDereference = true } // WithAppendSlice will make merge append slices instead of overwriting it. func WithAppendSlice(config *Config) { config.AppendSlice = true } // WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). func WithTypeCheck(config *Config) { config.TypeCheck = true } // WithSliceDeepCopy will merge slice element one by one with Overwrite flag. func WithSliceDeepCopy(config *Config) { config.sliceDeepCopy = true config.Overwrite = true } func merge(dst, src interface{}, opts ...func(*Config)) error { if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { return ErrNonPointerArgument } var ( vDst, vSrc reflect.Value err error ) config := &Config{} for _, opt := range opts { opt(config) } if vDst, vSrc, err = resolveValues(dst, src); err != nil { return err } if vDst.Type() != vSrc.Type() { return ErrDifferentArgumentsTypes } return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) } // IsReflectNil is the reflect value provided nil func isReflectNil(v reflect.Value) bool { k := v.Kind() switch k { case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: // Both interface and slice are nil if first word is 0. // Both are always bigger than a word; assume flagIndir. return v.IsNil() default: return false } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/imdario/mergo/map.go
vendor/github.com/imdario/mergo/map.go
// Copyright 2014 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Based on src/pkg/reflect/deepequal.go from official // golang's stdlib. package mergo import ( "fmt" "reflect" "unicode" "unicode/utf8" ) func changeInitialCase(s string, mapper func(rune) rune) string { if s == "" { return s } r, n := utf8.DecodeRuneInString(s) return string(mapper(r)) + s[n:] } func isExported(field reflect.StructField) bool { r, _ := utf8.DecodeRuneInString(field.Name) return r >= 'A' && r <= 'Z' } // Traverses recursively both values, assigning src's fields values to dst. // The map argument tracks comparisons that have already been seen, which allows // short circuiting on recursive types. func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { overwrite := config.Overwrite if dst.CanAddr() { addr := dst.UnsafeAddr() h := 17 * addr seen := visited[h] typ := dst.Type() for p := seen; p != nil; p = p.next { if p.ptr == addr && p.typ == typ { return nil } } // Remember, remember... visited[h] = &visit{typ, seen, addr} } zeroValue := reflect.Value{} switch dst.Kind() { case reflect.Map: dstMap := dst.Interface().(map[string]interface{}) for i, n := 0, src.NumField(); i < n; i++ { srcType := src.Type() field := srcType.Field(i) if !isExported(field) { continue } fieldName := field.Name fieldName = changeInitialCase(fieldName, unicode.ToLower) if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v), !config.ShouldNotDereference) || overwrite) { dstMap[fieldName] = src.Field(i).Interface() } } case reflect.Ptr: if dst.IsNil() { v := reflect.New(dst.Type().Elem()) dst.Set(v) } dst = dst.Elem() fallthrough case reflect.Struct: srcMap := src.Interface().(map[string]interface{}) for key := range srcMap { config.overwriteWithEmptyValue = true srcValue := srcMap[key] fieldName := changeInitialCase(key, unicode.ToUpper) dstElement := dst.FieldByName(fieldName) if dstElement == zeroValue { // We discard it because the field doesn't exist. continue } srcElement := reflect.ValueOf(srcValue) dstKind := dstElement.Kind() srcKind := srcElement.Kind() if srcKind == reflect.Ptr && dstKind != reflect.Ptr { srcElement = srcElement.Elem() srcKind = reflect.TypeOf(srcElement.Interface()).Kind() } else if dstKind == reflect.Ptr { // Can this work? I guess it can't. if srcKind != reflect.Ptr && srcElement.CanAddr() { srcPtr := srcElement.Addr() srcElement = reflect.ValueOf(srcPtr) srcKind = reflect.Ptr } } if !srcElement.IsValid() { continue } if srcKind == dstKind { if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface { if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else if srcKind == reflect.Map { if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else { return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind) } } } return } // Map sets fields' values in dst from src. // src can be a map with string keys or a struct. dst must be the opposite: // if src is a map, dst must be a valid pointer to struct. If src is a struct, // dst must be map[string]interface{}. // It won't merge unexported (private) fields and will do recursively // any exported field. // If dst is a map, keys will be src fields' names in lower camel case. // Missing key in src that doesn't match a field in dst will be skipped. This // doesn't apply if dst is a map. // This is separated method from Merge because it is cleaner and it keeps sane // semantics: merging equal types, mapping different (restricted) types. func Map(dst, src interface{}, opts ...func(*Config)) error { return _map(dst, src, opts...) } // MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by // non-empty src attribute values. // Deprecated: Use Map(…) with WithOverride func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { return _map(dst, src, append(opts, WithOverride)...) } func _map(dst, src interface{}, opts ...func(*Config)) error { if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr { return ErrNonPointerArgument } var ( vDst, vSrc reflect.Value err error ) config := &Config{} for _, opt := range opts { opt(config) } if vDst, vSrc, err = resolveValues(dst, src); err != nil { return err } // To be friction-less, we redirect equal-type arguments // to deepMerge. Only because arguments can be anything. if vSrc.Kind() == vDst.Kind() { return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) } switch vSrc.Kind() { case reflect.Struct: if vDst.Kind() != reflect.Map { return ErrExpectedMapAsDestination } case reflect.Map: if vDst.Kind() != reflect.Struct { return ErrExpectedStructAsDestination } default: return ErrNotSupported } return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/imdario/mergo/mergo.go
vendor/github.com/imdario/mergo/mergo.go
// Copyright 2013 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Based on src/pkg/reflect/deepequal.go from official // golang's stdlib. package mergo import ( "errors" "reflect" ) // Errors reported by Mergo when it finds invalid arguments. var ( ErrNilArguments = errors.New("src and dst must not be nil") ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") ErrNotSupported = errors.New("only structs, maps, and slices are supported") ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") ErrNonPointerArgument = errors.New("dst must be a pointer") ) // During deepMerge, must keep track of checks that are // in progress. The comparison algorithm assumes that all // checks in progress are true when it reencounters them. // Visited are stored in a map indexed by 17 * a1 + a2; type visit struct { typ reflect.Type next *visit ptr uintptr } // From src/pkg/encoding/json/encode.go. func isEmptyValue(v reflect.Value, shouldDereference bool) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: if v.IsNil() { return true } if shouldDereference { return isEmptyValue(v.Elem(), shouldDereference) } return false case reflect.Func: return v.IsNil() case reflect.Invalid: return true } return false } func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { if dst == nil || src == nil { err = ErrNilArguments return } vDst = reflect.ValueOf(dst).Elem() if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { err = ErrNotSupported return } vSrc = reflect.ValueOf(src) // We check if vSrc is a pointer to dereference it. if vSrc.Kind() == reflect.Ptr { vSrc = vSrc.Elem() } return }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/imdario/mergo/doc.go
vendor/github.com/imdario/mergo/doc.go
// Copyright 2013 Dario Castañé. All rights reserved. // Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). Status It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc. Important note Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules. Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code. If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u github.com/imdario/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0). Install Do your usual installation procedure: go get github.com/imdario/mergo // use in your .go code import ( "github.com/imdario/mergo" ) Usage You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). if err := mergo.Merge(&dst, src); err != nil { // ... } Also, you can merge overwriting values using the transformer WithOverride. if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil { // ... } Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. if err := mergo.Map(&dst, srcMap); err != nil { // ... } Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. Here is a nice example: package main import ( "fmt" "github.com/imdario/mergo" ) type Foo struct { A string B int64 } func main() { src := Foo{ A: "one", B: 2, } dest := Foo{ A: "two", } mergo.Merge(&dest, src) fmt.Println(dest) // Will print // {two 2} } Transformers Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time? package main import ( "fmt" "github.com/imdario/mergo" "reflect" "time" ) type timeTransformer struct { } func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error { if typ == reflect.TypeOf(time.Time{}) { return func(dst, src reflect.Value) error { if dst.CanSet() { isZero := dst.MethodByName("IsZero") result := isZero.Call([]reflect.Value{}) if result[0].Bool() { dst.Set(src) } } return nil } } return nil } type Snapshot struct { Time time.Time // ... } func main() { src := Snapshot{time.Now()} dest := Snapshot{} mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{})) fmt.Println(dest) // Will print // { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 } } Contact me If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario About Written by Dario Castañé: https://da.rio.hn License BSD 3-Clause license, as Go language. */ package mergo
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/sasha-s/go-deadlock/deadlock.go
vendor/github.com/sasha-s/go-deadlock/deadlock.go
package deadlock import ( "bufio" "bytes" "fmt" "io" "os" "sync" "time" "github.com/petermattis/goid" ) // Opts control how deadlock detection behaves. // Options are supposed to be set once at a startup (say, when parsing flags). var Opts = struct { // Mutex/RWMutex would work exactly as their sync counterparts // -- almost no runtime penalty, no deadlock detection if Disable == true. Disable bool // Would disable lock order based deadlock detection if DisableLockOrderDetection == true. DisableLockOrderDetection bool // Waiting for a lock for longer than DeadlockTimeout is considered a deadlock. // Ignored is DeadlockTimeout <= 0. DeadlockTimeout time.Duration // OnPotentialDeadlock is called each time a potential deadlock is detected -- either based on // lock order or on lock wait time. OnPotentialDeadlock func() // Will keep MaxMapSize lock pairs (happens before // happens after) in the map. // The map resets once the threshold is reached. MaxMapSize int // Will dump stacktraces of all goroutines when inconsistent locking is detected. PrintAllCurrentGoroutines bool mu *sync.Mutex // Protects the LogBuf. // Will print deadlock info to log buffer. LogBuf io.Writer }{ DeadlockTimeout: time.Second * 30, OnPotentialDeadlock: func() { os.Exit(2) }, MaxMapSize: 1024 * 64, mu: &sync.Mutex{}, LogBuf: os.Stderr, } // Cond is sync.Cond wrapper type Cond struct { sync.Cond } // Locker is sync.Locker wrapper type Locker struct { sync.Locker } // Once is sync.Once wrapper type Once struct { sync.Once } // Pool is sync.Poll wrapper type Pool struct { sync.Pool } // WaitGroup is sync.WaitGroup wrapper type WaitGroup struct { sync.WaitGroup } // A Mutex is a drop-in replacement for sync.Mutex. // Performs deadlock detection unless disabled in Opts. type Mutex struct { mu sync.Mutex } // Lock locks the mutex. // If the lock is already in use, the calling goroutine // blocks until the mutex is available. // // Unless deadlock detection is disabled, logs potential deadlocks to Opts.LogBuf, // calling Opts.OnPotentialDeadlock on each occasion. func (m *Mutex) Lock() { lock(m.mu.Lock, m) } // Unlock unlocks the mutex. // It is a run-time error if m is not locked on entry to Unlock. // // A locked Mutex is not associated with a particular goroutine. // It is allowed for one goroutine to lock a Mutex and then // arrange for another goroutine to unlock it. func (m *Mutex) Unlock() { m.mu.Unlock() if !Opts.Disable { postUnlock(m) } } // An RWMutex is a drop-in replacement for sync.RWMutex. // Performs deadlock detection unless disabled in Opts. type RWMutex struct { mu sync.RWMutex } // Lock locks rw for writing. // If the lock is already locked for reading or writing, // Lock blocks until the lock is available. // To ensure that the lock eventually becomes available, // a blocked Lock call excludes new readers from acquiring // the lock. // // Unless deadlock detection is disabled, logs potential deadlocks to Opts.LogBuf, // calling Opts.OnPotentialDeadlock on each occasion. func (m *RWMutex) Lock() { lock(m.mu.Lock, m) } // Unlock unlocks the mutex for writing. It is a run-time error if rw is // not locked for writing on entry to Unlock. // // As with Mutexes, a locked RWMutex is not associated with a particular // goroutine. One goroutine may RLock (Lock) an RWMutex and then // arrange for another goroutine to RUnlock (Unlock) it. func (m *RWMutex) Unlock() { m.mu.Unlock() if !Opts.Disable { postUnlock(m) } } // RLock locks the mutex for reading. // // Unless deadlock detection is disabled, logs potential deadlocks to Opts.LogBuf, // calling Opts.OnPotentialDeadlock on each occasion. func (m *RWMutex) RLock() { lock(m.mu.RLock, m) } // RUnlock undoes a single RLock call; // it does not affect other simultaneous readers. // It is a run-time error if rw is not locked for reading // on entry to RUnlock. func (m *RWMutex) RUnlock() { m.mu.RUnlock() if !Opts.Disable { postUnlock(m) } } // RLocker returns a Locker interface that implements // the Lock and Unlock methods by calling RLock and RUnlock. func (m *RWMutex) RLocker() sync.Locker { return (*rlocker)(m) } func preLock(stack []uintptr, p interface{}) { lo.preLock(stack, p) } func postLock(stack []uintptr, p interface{}) { lo.postLock(stack, p) } func postUnlock(p interface{}) { lo.postUnlock(p) } func lock(lockFn func(), ptr interface{}) { if Opts.Disable { lockFn() return } stack := callers(1) preLock(stack, ptr) if Opts.DeadlockTimeout <= 0 { lockFn() } else { ch := make(chan struct{}) currentID := goid.Get() go func() { for { t := time.NewTimer(Opts.DeadlockTimeout) defer t.Stop() // This runs after the losure finishes, but it's OK. select { case <-t.C: lo.mu.Lock() prev, ok := lo.cur[ptr] if !ok { lo.mu.Unlock() break // Nobody seems to be holding the lock, try again. } Opts.mu.Lock() fmt.Fprintln(Opts.LogBuf, header) fmt.Fprintln(Opts.LogBuf, "Previous place where the lock was grabbed") fmt.Fprintf(Opts.LogBuf, "goroutine %v lock %p\n", prev.gid, ptr) printStack(Opts.LogBuf, prev.stack) fmt.Fprintln(Opts.LogBuf, "Have been trying to lock it again for more than", Opts.DeadlockTimeout) fmt.Fprintf(Opts.LogBuf, "goroutine %v lock %p\n", currentID, ptr) printStack(Opts.LogBuf, stack) stacks := stacks() grs := bytes.Split(stacks, []byte("\n\n")) for _, g := range grs { if goid.ExtractGID(g) == prev.gid { fmt.Fprintln(Opts.LogBuf, "Here is what goroutine", prev.gid, "doing now") Opts.LogBuf.Write(g) fmt.Fprintln(Opts.LogBuf) } } lo.other(ptr) if Opts.PrintAllCurrentGoroutines { fmt.Fprintln(Opts.LogBuf, "All current goroutines:") Opts.LogBuf.Write(stacks) } fmt.Fprintln(Opts.LogBuf) if buf, ok := Opts.LogBuf.(*bufio.Writer); ok { buf.Flush() } Opts.mu.Unlock() lo.mu.Unlock() Opts.OnPotentialDeadlock() <-ch return case <-ch: return } } }() lockFn() postLock(stack, ptr) close(ch) return } postLock(stack, ptr) } type lockOrder struct { mu sync.Mutex cur map[interface{}]stackGID // stacktraces + gids for the locks currently taken. order map[beforeAfter]ss // expected order of locks. } type stackGID struct { stack []uintptr gid int64 } type beforeAfter struct { before interface{} after interface{} } type ss struct { before []uintptr after []uintptr } var lo = newLockOrder() func newLockOrder() *lockOrder { return &lockOrder{ cur: map[interface{}]stackGID{}, order: map[beforeAfter]ss{}, } } func (l *lockOrder) postLock(stack []uintptr, p interface{}) { gid := goid.Get() l.mu.Lock() l.cur[p] = stackGID{stack, gid} l.mu.Unlock() } func (l *lockOrder) preLock(stack []uintptr, p interface{}) { if Opts.DisableLockOrderDetection { return } gid := goid.Get() l.mu.Lock() for b, bs := range l.cur { if b == p { if bs.gid == gid { Opts.mu.Lock() fmt.Fprintln(Opts.LogBuf, header, "Recursive locking:") fmt.Fprintf(Opts.LogBuf, "current goroutine %d lock %p\n", gid, b) printStack(Opts.LogBuf, stack) fmt.Fprintln(Opts.LogBuf, "Previous place where the lock was grabbed (same goroutine)") printStack(Opts.LogBuf, bs.stack) l.other(p) if buf, ok := Opts.LogBuf.(*bufio.Writer); ok { buf.Flush() } Opts.mu.Unlock() Opts.OnPotentialDeadlock() } continue } if bs.gid != gid { // We want locks taken in the same goroutine only. continue } if s, ok := l.order[beforeAfter{p, b}]; ok { Opts.mu.Lock() fmt.Fprintln(Opts.LogBuf, header, "Inconsistent locking. saw this ordering in one goroutine:") fmt.Fprintln(Opts.LogBuf, "happened before") printStack(Opts.LogBuf, s.before) fmt.Fprintln(Opts.LogBuf, "happened after") printStack(Opts.LogBuf, s.after) fmt.Fprintln(Opts.LogBuf, "in another goroutine: happened before") printStack(Opts.LogBuf, bs.stack) fmt.Fprintln(Opts.LogBuf, "happened after") printStack(Opts.LogBuf, stack) l.other(p) fmt.Fprintln(Opts.LogBuf) if buf, ok := Opts.LogBuf.(*bufio.Writer); ok { buf.Flush() } Opts.mu.Unlock() Opts.OnPotentialDeadlock() } l.order[beforeAfter{b, p}] = ss{bs.stack, stack} if len(l.order) == Opts.MaxMapSize { // Reset the map to keep memory footprint bounded. l.order = map[beforeAfter]ss{} } } l.mu.Unlock() } func (l *lockOrder) postUnlock(p interface{}) { l.mu.Lock() delete(l.cur, p) l.mu.Unlock() } type rlocker RWMutex func (r *rlocker) Lock() { (*RWMutex)(r).RLock() } func (r *rlocker) Unlock() { (*RWMutex)(r).RUnlock() } // Under lo.mu Locked. func (l *lockOrder) other(ptr interface{}) { empty := true for k := range l.cur { if k == ptr { continue } empty = false } if empty { return } fmt.Fprintln(Opts.LogBuf, "Other goroutines holding locks:") for k, pp := range l.cur { if k == ptr { continue } fmt.Fprintf(Opts.LogBuf, "goroutine %v lock %p\n", pp.gid, k) printStack(Opts.LogBuf, pp.stack) } fmt.Fprintln(Opts.LogBuf) } const header = "POTENTIAL DEADLOCK:"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/sasha-s/go-deadlock/deadlock_map.go
vendor/github.com/sasha-s/go-deadlock/deadlock_map.go
// +build go1.9 package deadlock import "sync" // Map is sync.Map wrapper type Map struct { sync.Map }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/sasha-s/go-deadlock/stacktraces.go
vendor/github.com/sasha-s/go-deadlock/stacktraces.go
package deadlock import ( "bytes" "fmt" "io" "io/ioutil" "os" "os/user" "path/filepath" "runtime" "strings" "sync" ) func callers(skip int) []uintptr { s := make([]uintptr, 50) // Most relevant context seem to appear near the top of the stack. return s[:runtime.Callers(2+skip, s)] } func printStack(w io.Writer, stack []uintptr) { home := os.Getenv("HOME") usr, err := user.Current() if err == nil { home = usr.HomeDir } cwd, _ := os.Getwd() for i, pc := range stack { f := runtime.FuncForPC(pc) name := f.Name() pkg := "" if pos := strings.LastIndex(name, "/"); pos >= 0 { name = name[pos+1:] } if pos := strings.Index(name, "."); pos >= 0 { pkg = name[:pos] name = name[pos+1:] } file, line := f.FileLine(pc) if (pkg == "runtime" && name == "goexit") || (pkg == "testing" && name == "tRunner") { fmt.Fprintln(w) return } tail := "" if i == 0 { tail = " <<<<<" // Make the line performing a lock prominent. } // Shorten the file name. clean := file if cwd != "" { cl, err := filepath.Rel(cwd, file) if err == nil { clean = cl } } if home != "" { s2 := strings.Replace(file, home, "~", 1) if len(clean) > len(s2) { clean = s2 } } fmt.Fprintf(w, "%s:%d %s.%s %s%s\n", clean, line-1, pkg, name, code(file, line), tail) } fmt.Fprintln(w) } var fileSources struct { sync.Mutex lines map[string][][]byte } // Reads souce file lines from disk if not cached already. func getSourceLines(file string) [][]byte { fileSources.Lock() defer fileSources.Unlock() if fileSources.lines == nil { fileSources.lines = map[string][][]byte{} } if lines, ok := fileSources.lines[file]; ok { return lines } text, _ := ioutil.ReadFile(file) fileSources.lines[file] = bytes.Split(text, []byte{'\n'}) return fileSources.lines[file] } func code(file string, line int) string { lines := getSourceLines(file) line -= 2 if line >= len(lines) || line < 0 { return "???" } return "{ " + string(bytes.TrimSpace(lines[line])) + " }" } // Stacktraces for all goroutines. func stacks() []byte { buf := make([]byte, 1024*16) for { n := runtime.Stack(buf, true) if n < len(buf) { return buf[:n] } buf = make([]byte, 2*len(buf)) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/boz/go-throttle/throttle.go
vendor/github.com/boz/go-throttle/throttle.go
// Package throttle provides functionality to limit the frequency with which code is called // // Throttling is of the Trigger() method and depends on the parameters passed (period, trailing). // // The period parameter defines how often the throttled code can run. A period of one second means // that the throttled code will run at most once per second. // // The trailing parameter defines what hapens if Trigger() is called after the throttled code has been // started, but before the period is finished. If trailing is false then these triggers are ignored. // If trailing is true then the throttled code is executed one more time at the beginning of the next period. // // Example with period = time.Second and trailing = false: // // Whole seconds after first trigger...|0|0|0|0|1|1|1|1| // Trigger() gets called...............|X| |X| | |X| | | // Throttled code gets called..........|X| | | | |X| | | // // Note that the second trigger had no effect. The third Trigger() caused immediate execution of the // throttled code. // // Example with period = time.Second and trailing = true: // // Whole seconds after first trigger...|0|0|0|0|1|1|1|1| // Trigger() gets called...............|X| |X| | |X| | | // Throttled code gets called..........|X| | | |X| | | | // // Note that the second Trigger() causes the throttled code to get called once the first period is over. // The third Trigger() will do the same. package throttle import ( "sync" "time" ) // ThrottleDriver is an interface for requesting execution of the throttled resource // and for stopping the throttler. type ThrottleDriver interface { // Trigger() requests execution of the throttled resource. Trigger() // Stop() stops the throttler. Stop() } // Throttle extends ThrottleDriver with Next(), which is used by the client to throttle its code. type Throttle interface { ThrottleDriver // Next() returns true at most once per `period`. If false is returned the throttler has been stoped. Next() bool } // NewThrottle returns a new Throttle. If trailing is true then a multiple Trigger() calls in one // period will cause a delayed Trigger() to be called in the next period. func NewThrottle(period time.Duration, trailing bool) Throttle { return newThrottler(period, trailing) } // ThottleFunc executes f at most once every period. Stop() must eventually be called // on the return value to prevent a leaked go proc. func ThrottleFunc(period time.Duration, trailing bool, f func()) ThrottleDriver { throttler := newThrottler(period, trailing) go func() { for throttler.Next() { f() } }() return throttler } type throttler struct { cond *sync.Cond period time.Duration trailing bool last time.Time waiting bool stop bool } func newThrottler(period time.Duration, trailing bool) *throttler { return &throttler{ period: period, trailing: trailing, cond: sync.NewCond(&sync.Mutex{}), } } // Trigger signals an attempt to execute the throttled code. // If Trigger is called twice within the same period, Next() will be called once for that period // (and once for the next period if trailing is true). func (t *throttler) Trigger() { t.cond.L.Lock() defer t.cond.L.Unlock() if !t.waiting && !t.stop { delta := time.Now().Sub(t.last) if delta > t.period { t.waiting = true t.cond.Broadcast() } else if t.trailing { t.waiting = true time.AfterFunc(t.period-delta, t.cond.Broadcast) } } } // Next() returns true at most once per period. While it returns true, the throttle is running. // When it returns false the throttle has been stopped. func (t *throttler) Next() bool { t.cond.L.Lock() defer t.cond.L.Unlock() for !t.waiting && !t.stop { t.cond.Wait() } if !t.stop { t.waiting = false t.last = time.Now() } return !t.stop } // Stop the throttle func (t *throttler) Stop() { t.cond.L.Lock() defer t.cond.L.Unlock() t.stop = true t.cond.Broadcast() }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-units/size.go
vendor/github.com/docker/go-units/size.go
package units import ( "fmt" "strconv" "strings" ) // See: http://en.wikipedia.org/wiki/Binary_prefix const ( // Decimal KB = 1000 MB = 1000 * KB GB = 1000 * MB TB = 1000 * GB PB = 1000 * TB // Binary KiB = 1024 MiB = 1024 * KiB GiB = 1024 * MiB TiB = 1024 * GiB PiB = 1024 * TiB ) type unitMap map[byte]int64 var ( decimalMap = unitMap{'k': KB, 'm': MB, 'g': GB, 't': TB, 'p': PB} binaryMap = unitMap{'k': KiB, 'm': MiB, 'g': GiB, 't': TiB, 'p': PiB} ) var ( decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} ) func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) { i := 0 unitsLimit := len(_map) - 1 for size >= base && i < unitsLimit { size = size / base i++ } return size, _map[i] } // CustomSize returns a human-readable approximation of a size // using custom format. func CustomSize(format string, size float64, base float64, _map []string) string { size, unit := getSizeAndUnit(size, base, _map) return fmt.Sprintf(format, size, unit) } // HumanSizeWithPrecision allows the size to be in any precision, // instead of 4 digit precision used in units.HumanSize. func HumanSizeWithPrecision(size float64, precision int) string { size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs) return fmt.Sprintf("%.*g%s", precision, size, unit) } // HumanSize returns a human-readable approximation of a size // capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). func HumanSize(size float64) string { return HumanSizeWithPrecision(size, 4) } // BytesSize returns a human-readable size in bytes, kibibytes, // mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). func BytesSize(size float64) string { return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs) } // FromHumanSize returns an integer from a human-readable specification of a // size using SI standard (eg. "44kB", "17MB"). func FromHumanSize(size string) (int64, error) { return parseSize(size, decimalMap) } // RAMInBytes parses a human-readable string representing an amount of RAM // in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and // returns the number of bytes, or -1 if the string is unparseable. // Units are case-insensitive, and the 'b' suffix is optional. func RAMInBytes(size string) (int64, error) { return parseSize(size, binaryMap) } // Parses the human-readable size string into the amount it represents. func parseSize(sizeStr string, uMap unitMap) (int64, error) { // TODO: rewrite to use strings.Cut if there's a space // once Go < 1.18 is deprecated. sep := strings.LastIndexAny(sizeStr, "01234567890. ") if sep == -1 { // There should be at least a digit. return -1, fmt.Errorf("invalid size: '%s'", sizeStr) } var num, sfx string if sizeStr[sep] != ' ' { num = sizeStr[:sep+1] sfx = sizeStr[sep+1:] } else { // Omit the space separator. num = sizeStr[:sep] sfx = sizeStr[sep+1:] } size, err := strconv.ParseFloat(num, 64) if err != nil { return -1, err } // Backward compatibility: reject negative sizes. if size < 0 { return -1, fmt.Errorf("invalid size: '%s'", sizeStr) } if len(sfx) == 0 { return int64(size), nil } // Process the suffix. if len(sfx) > 3 { // Too long. goto badSuffix } sfx = strings.ToLower(sfx) // Trivial case: b suffix. if sfx[0] == 'b' { if len(sfx) > 1 { // no extra characters allowed after b. goto badSuffix } return int64(size), nil } // A suffix from the map. if mul, ok := uMap[sfx[0]]; ok { size *= float64(mul) } else { goto badSuffix } // The suffix may have extra "b" or "ib" (e.g. KiB or MB). switch { case len(sfx) == 2 && sfx[1] != 'b': goto badSuffix case len(sfx) == 3 && sfx[1:] != "ib": goto badSuffix } return int64(size), nil badSuffix: return -1, fmt.Errorf("invalid suffix: '%s'", sfx) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-units/ulimit.go
vendor/github.com/docker/go-units/ulimit.go
package units import ( "fmt" "strconv" "strings" ) // Ulimit is a human friendly version of Rlimit. type Ulimit struct { Name string Hard int64 Soft int64 } // Rlimit specifies the resource limits, such as max open files. type Rlimit struct { Type int `json:"type,omitempty"` Hard uint64 `json:"hard,omitempty"` Soft uint64 `json:"soft,omitempty"` } const ( // magic numbers for making the syscall // some of these are defined in the syscall package, but not all. // Also since Windows client doesn't get access to the syscall package, need to // define these here rlimitAs = 9 rlimitCore = 4 rlimitCPU = 0 rlimitData = 2 rlimitFsize = 1 rlimitLocks = 10 rlimitMemlock = 8 rlimitMsgqueue = 12 rlimitNice = 13 rlimitNofile = 7 rlimitNproc = 6 rlimitRss = 5 rlimitRtprio = 14 rlimitRttime = 15 rlimitSigpending = 11 rlimitStack = 3 ) var ulimitNameMapping = map[string]int{ //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container. "core": rlimitCore, "cpu": rlimitCPU, "data": rlimitData, "fsize": rlimitFsize, "locks": rlimitLocks, "memlock": rlimitMemlock, "msgqueue": rlimitMsgqueue, "nice": rlimitNice, "nofile": rlimitNofile, "nproc": rlimitNproc, "rss": rlimitRss, "rtprio": rlimitRtprio, "rttime": rlimitRttime, "sigpending": rlimitSigpending, "stack": rlimitStack, } // ParseUlimit parses and returns a Ulimit from the specified string. func ParseUlimit(val string) (*Ulimit, error) { parts := strings.SplitN(val, "=", 2) if len(parts) != 2 { return nil, fmt.Errorf("invalid ulimit argument: %s", val) } if _, exists := ulimitNameMapping[parts[0]]; !exists { return nil, fmt.Errorf("invalid ulimit type: %s", parts[0]) } var ( soft int64 hard = &soft // default to soft in case no hard was set temp int64 err error ) switch limitVals := strings.Split(parts[1], ":"); len(limitVals) { case 2: temp, err = strconv.ParseInt(limitVals[1], 10, 64) if err != nil { return nil, err } hard = &temp fallthrough case 1: soft, err = strconv.ParseInt(limitVals[0], 10, 64) if err != nil { return nil, err } default: return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) } if *hard != -1 { if soft == -1 { return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: soft: -1 (unlimited), hard: %d", *hard) } if soft > *hard { return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard) } } return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil } // GetRlimit returns the RLimit corresponding to Ulimit. func (u *Ulimit) GetRlimit() (*Rlimit, error) { t, exists := ulimitNameMapping[u.Name] if !exists { return nil, fmt.Errorf("invalid ulimit name %s", u.Name) } return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil } func (u *Ulimit) String() string { return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-units/duration.go
vendor/github.com/docker/go-units/duration.go
// Package units provides helper function to parse and print size and time units // in human-readable format. package units import ( "fmt" "time" ) // HumanDuration returns a human-readable approximation of a duration // (eg. "About a minute", "4 hours ago", etc.). func HumanDuration(d time.Duration) string { if seconds := int(d.Seconds()); seconds < 1 { return "Less than a second" } else if seconds == 1 { return "1 second" } else if seconds < 60 { return fmt.Sprintf("%d seconds", seconds) } else if minutes := int(d.Minutes()); minutes == 1 { return "About a minute" } else if minutes < 60 { return fmt.Sprintf("%d minutes", minutes) } else if hours := int(d.Hours() + 0.5); hours == 1 { return "About an hour" } else if hours < 48 { return fmt.Sprintf("%d hours", hours) } else if hours < 24*7*2 { return fmt.Sprintf("%d days", hours/24) } else if hours < 24*30*2 { return fmt.Sprintf("%d weeks", hours/24/7) } else if hours < 24*365*2 { return fmt.Sprintf("%d months", hours/24/30) } return fmt.Sprintf("%d years", int(d.Hours())/24/365) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/proxy.go
vendor/github.com/docker/go-connections/sockets/proxy.go
package sockets import ( "net" "os" "strings" ) // GetProxyEnv allows access to the uppercase and the lowercase forms of // proxy-related variables. See the Go specification for details on these // variables. https://golang.org/pkg/net/http/ func GetProxyEnv(key string) string { proxyValue := os.Getenv(strings.ToUpper(key)) if proxyValue == "" { return os.Getenv(strings.ToLower(key)) } return proxyValue } // DialerFromEnvironment was previously used to configure a net.Dialer to route // connections through a SOCKS proxy. // DEPRECATED: SOCKS proxies are now supported by configuring only // http.Transport.Proxy, and no longer require changing http.Transport.Dial. // Therefore, only sockets.ConfigureTransport() needs to be called, and any // sockets.DialerFromEnvironment() calls can be dropped. func DialerFromEnvironment(direct *net.Dialer) (*net.Dialer, error) { return direct, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/sockets.go
vendor/github.com/docker/go-connections/sockets/sockets.go
// Package sockets provides helper functions to create and configure Unix or TCP sockets. package sockets import ( "errors" "net" "net/http" "time" ) const defaultTimeout = 10 * time.Second // ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system. var ErrProtocolNotAvailable = errors.New("protocol not available") // ConfigureTransport configures the specified [http.Transport] according to the specified proto // and addr. // // If the proto is unix (using a unix socket to communicate) or npipe the compression is disabled. // For other protos, compression is enabled. If you want to manually enable/disable compression, // make sure you do it _after_ any subsequent calls to ConfigureTransport is made against the same // [http.Transport]. func ConfigureTransport(tr *http.Transport, proto, addr string) error { switch proto { case "unix": return configureUnixTransport(tr, proto, addr) case "npipe": return configureNpipeTransport(tr, proto, addr) default: tr.Proxy = http.ProxyFromEnvironment tr.DisableCompression = false tr.DialContext = (&net.Dialer{ Timeout: defaultTimeout, }).DialContext } return nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/inmem_socket.go
vendor/github.com/docker/go-connections/sockets/inmem_socket.go
package sockets import ( "errors" "net" "sync" ) var errClosed = errors.New("use of closed network connection") // InmemSocket implements net.Listener using in-memory only connections. type InmemSocket struct { chConn chan net.Conn chClose chan struct{} addr string mu sync.Mutex } // dummyAddr is used to satisfy net.Addr for the in-mem socket // it is just stored as a string and returns the string for all calls type dummyAddr string // NewInmemSocket creates an in-memory only net.Listener // The addr argument can be any string, but is used to satisfy the `Addr()` part // of the net.Listener interface func NewInmemSocket(addr string, bufSize int) *InmemSocket { return &InmemSocket{ chConn: make(chan net.Conn, bufSize), chClose: make(chan struct{}), addr: addr, } } // Addr returns the socket's addr string to satisfy net.Listener func (s *InmemSocket) Addr() net.Addr { return dummyAddr(s.addr) } // Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn. func (s *InmemSocket) Accept() (net.Conn, error) { select { case conn := <-s.chConn: return conn, nil case <-s.chClose: return nil, errClosed } } // Close closes the listener. It will be unavailable for use once closed. func (s *InmemSocket) Close() error { s.mu.Lock() defer s.mu.Unlock() select { case <-s.chClose: default: close(s.chClose) } return nil } // Dial is used to establish a connection with the in-mem server func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) { srvConn, clientConn := net.Pipe() select { case s.chConn <- srvConn: case <-s.chClose: return nil, errClosed } return clientConn, nil } // Network returns the addr string, satisfies net.Addr func (a dummyAddr) Network() string { return string(a) } // String returns the string form func (a dummyAddr) String() string { return string(a) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/sockets_windows.go
vendor/github.com/docker/go-connections/sockets/sockets_windows.go
package sockets import ( "context" "net" "net/http" "time" "github.com/Microsoft/go-winio" ) func configureUnixTransport(tr *http.Transport, proto, addr string) error { return ErrProtocolNotAvailable } func configureNpipeTransport(tr *http.Transport, proto, addr string) error { // No need for compression in local communications. tr.DisableCompression = true tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { return winio.DialPipeContext(ctx, addr) } return nil } // DialPipe connects to a Windows named pipe. func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { return winio.DialPipe(addr, &timeout) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/tcp_socket.go
vendor/github.com/docker/go-connections/sockets/tcp_socket.go
// Package sockets provides helper functions to create and configure Unix or TCP sockets. package sockets import ( "crypto/tls" "net" ) // NewTCPSocket creates a TCP socket listener with the specified address and // the specified tls configuration. If TLSConfig is set, will encapsulate the // TCP listener inside a TLS one. func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) { l, err := net.Listen("tcp", addr) if err != nil { return nil, err } if tlsConfig != nil { tlsConfig.NextProtos = []string{"http/1.1"} l = tls.NewListener(l, tlsConfig) } return l, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/unix_socket.go
vendor/github.com/docker/go-connections/sockets/unix_socket.go
//go:build !windows /* Package sockets is a simple unix domain socket wrapper. # Usage For example: import( "fmt" "net" "os" "github.com/docker/go-connections/sockets" ) func main() { l, err := sockets.NewUnixSocketWithOpts("/path/to/sockets", sockets.WithChown(0,0),sockets.WithChmod(0660)) if err != nil { panic(err) } echoStr := "hello" go func() { for { conn, err := l.Accept() if err != nil { return } conn.Write([]byte(echoStr)) conn.Close() } }() conn, err := net.Dial("unix", path) if err != nil { t.Fatal(err) } buf := make([]byte, 5) if _, err := conn.Read(buf); err != nil { panic(err) } else if string(buf) != echoStr { panic(fmt.Errorf("msg may lost")) } } */ package sockets import ( "net" "os" "syscall" ) // SockOption sets up socket file's creating option type SockOption func(string) error // WithChown modifies the socket file's uid and gid func WithChown(uid, gid int) SockOption { return func(path string) error { if err := os.Chown(path, uid, gid); err != nil { return err } return nil } } // WithChmod modifies socket file's access mode. func WithChmod(mask os.FileMode) SockOption { return func(path string) error { if err := os.Chmod(path, mask); err != nil { return err } return nil } } // NewUnixSocketWithOpts creates a unix socket with the specified options. // By default, socket permissions are 0000 (i.e.: no access for anyone); pass // WithChmod() and WithChown() to set the desired ownership and permissions. // // This function temporarily changes the system's "umask" to 0777 to work around // a race condition between creating the socket and setting its permissions. While // this should only be for a short duration, it may affect other processes that // create files/directories during that period. func NewUnixSocketWithOpts(path string, opts ...SockOption) (net.Listener, error) { if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { return nil, err } // net.Listen does not allow for permissions to be set. As a result, when // specifying custom permissions ("WithChmod()"), there is a short time // between creating the socket and applying the permissions, during which // the socket permissions are Less restrictive than desired. // // To work around this limitation of net.Listen(), we temporarily set the // umask to 0777, which forces the socket to be created with 000 permissions // (i.e.: no access for anyone). After that, WithChmod() must be used to set // the desired permissions. // // We don't use "defer" here, to reset the umask to its original value as soon // as possible. Ideally we'd be able to detect if WithChmod() was passed as // an option, and skip changing umask if default permissions are used. origUmask := syscall.Umask(0o777) l, err := net.Listen("unix", path) syscall.Umask(origUmask) if err != nil { return nil, err } for _, op := range opts { if err := op(path); err != nil { _ = l.Close() return nil, err } } return l, nil } // NewUnixSocket creates a unix socket with the specified path and group. func NewUnixSocket(path string, gid int) (net.Listener, error) { return NewUnixSocketWithOpts(path, WithChown(0, gid), WithChmod(0o660)) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/sockets/sockets_unix.go
vendor/github.com/docker/go-connections/sockets/sockets_unix.go
//go:build !windows package sockets import ( "context" "fmt" "net" "net/http" "syscall" "time" ) const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path) func configureUnixTransport(tr *http.Transport, proto, addr string) error { if len(addr) > maxUnixSocketPathSize { return fmt.Errorf("unix socket path %q is too long", addr) } // No need for compression in local communications. tr.DisableCompression = true dialer := &net.Dialer{ Timeout: defaultTimeout, } tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { return dialer.DialContext(ctx, proto, addr) } return nil } func configureNpipeTransport(tr *http.Transport, proto, addr string) error { return ErrProtocolNotAvailable } // DialPipe connects to a Windows named pipe. // This is not supported on other OSes. func DialPipe(_ string, _ time.Duration) (net.Conn, error) { return nil, syscall.EAFNOSUPPORT }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go
vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go
// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. package tlsconfig import ( "crypto/tls" ) // Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) var clientCipherSuites = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/tlsconfig/config.go
vendor/github.com/docker/go-connections/tlsconfig/config.go
// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. // // As a reminder from https://golang.org/pkg/crypto/tls/#Config: // // A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. // A Config may be reused; the tls package will also not modify it. package tlsconfig import ( "crypto/tls" "crypto/x509" "encoding/pem" "errors" "fmt" "os" ) // Options represents the information needed to create client and server TLS configurations. type Options struct { CAFile string // If either CertFile or KeyFile is empty, Client() will not load them // preventing the client from authenticating to the server. // However, Server() requires them and will error out if they are empty. CertFile string KeyFile string // client-only option InsecureSkipVerify bool // server-only option ClientAuth tls.ClientAuthType // If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS // creds will include exclusively the roots in that CA file. If no CA file is provided, // the system pool will be used. ExclusiveRootPools bool MinVersion uint16 // If Passphrase is set, it will be used to decrypt a TLS private key // if the key is encrypted. // // Deprecated: Use of encrypted TLS private keys has been deprecated, and // will be removed in a future release. Golang has deprecated support for // legacy PEM encryption (as specified in RFC 1423), as it is insecure by // design (see https://go-review.googlesource.com/c/go/+/264159). Passphrase string } // Extra (server-side) accepted CBC cipher suites - will phase out in the future var acceptedCBCCiphers = []uint16{ tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, } // DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls // options struct but wants to use a commonly accepted set of TLS cipher suites, with // known weak algorithms removed. var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...) // ServerDefault returns a secure-enough TLS configuration for the server TLS configuration. func ServerDefault(ops ...func(*tls.Config)) *tls.Config { tlsConfig := &tls.Config{ // Avoid fallback by default to SSL protocols < TLS1.2 MinVersion: tls.VersionTLS12, PreferServerCipherSuites: true, CipherSuites: DefaultServerAcceptedCiphers, } for _, op := range ops { op(tlsConfig) } return tlsConfig } // ClientDefault returns a secure-enough TLS configuration for the client TLS configuration. func ClientDefault(ops ...func(*tls.Config)) *tls.Config { tlsConfig := &tls.Config{ // Prefer TLS1.2 as the client minimum MinVersion: tls.VersionTLS12, CipherSuites: clientCipherSuites, } for _, op := range ops { op(tlsConfig) } return tlsConfig } // certPool returns an X.509 certificate pool from `caFile`, the certificate file. func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { // If we should verify the server, we need to load a trusted ca var ( certPool *x509.CertPool err error ) if exclusivePool { certPool = x509.NewCertPool() } else { certPool, err = SystemCertPool() if err != nil { return nil, fmt.Errorf("failed to read system certificates: %v", err) } } pemData, err := os.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) } if !certPool.AppendCertsFromPEM(pemData) { return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) } return certPool, nil } // allTLSVersions lists all the TLS versions and is used by the code that validates // a uint16 value as a TLS version. var allTLSVersions = map[uint16]struct{}{ tls.VersionTLS10: {}, tls.VersionTLS11: {}, tls.VersionTLS12: {}, tls.VersionTLS13: {}, } // isValidMinVersion checks that the input value is a valid tls minimum version func isValidMinVersion(version uint16) bool { _, ok := allTLSVersions[version] return ok } // adjustMinVersion sets the MinVersion on `config`, the input configuration. // It assumes the current MinVersion on the `config` is the lowest allowed. func adjustMinVersion(options Options, config *tls.Config) error { if options.MinVersion > 0 { if !isValidMinVersion(options.MinVersion) { return fmt.Errorf("invalid minimum TLS version: %x", options.MinVersion) } if options.MinVersion < config.MinVersion { return fmt.Errorf("requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) } config.MinVersion = options.MinVersion } return nil } // IsErrEncryptedKey returns true if the 'err' is an error of incorrect // password when trying to decrypt a TLS private key. // // Deprecated: Use of encrypted TLS private keys has been deprecated, and // will be removed in a future release. Golang has deprecated support for // legacy PEM encryption (as specified in RFC 1423), as it is insecure by // design (see https://go-review.googlesource.com/c/go/+/264159). func IsErrEncryptedKey(err error) bool { return errors.Is(err, x509.IncorrectPasswordError) } // getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format. // If the private key is encrypted, 'passphrase' is used to decrypted the // private key. func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { // this section makes some small changes to code from notary/tuf/utils/x509.go pemBlock, _ := pem.Decode(keyBytes) if pemBlock == nil { return nil, fmt.Errorf("no valid private key found") } var err error if x509.IsEncryptedPEMBlock(pemBlock) { //nolint:staticcheck // Ignore SA1019 (IsEncryptedPEMBlock is deprecated) keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) //nolint:staticcheck // Ignore SA1019 (DecryptPEMBlock is deprecated) if err != nil { return nil, fmt.Errorf("private key is encrypted, but could not decrypt it: %w", err) } keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) } return keyBytes, nil } // getCert returns a Certificate from the CertFile and KeyFile in 'options', // if the key is encrypted, the Passphrase in 'options' will be used to // decrypt it. func getCert(options Options) ([]tls.Certificate, error) { if options.CertFile == "" && options.KeyFile == "" { return nil, nil } cert, err := os.ReadFile(options.CertFile) if err != nil { return nil, err } prKeyBytes, err := os.ReadFile(options.KeyFile) if err != nil { return nil, err } prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) if err != nil { return nil, err } tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) if err != nil { return nil, err } return []tls.Certificate{tlsCert}, nil } // Client returns a TLS configuration meant to be used by a client. func Client(options Options) (*tls.Config, error) { tlsConfig := ClientDefault() tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify if !options.InsecureSkipVerify && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.RootCAs = CAs } tlsCerts, err := getCert(options) if err != nil { return nil, fmt.Errorf("could not load X509 key pair: %w", err) } tlsConfig.Certificates = tlsCerts if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil } // Server returns a TLS configuration meant to be used by a server. func Server(options Options) (*tls.Config, error) { tlsConfig := ServerDefault() tlsConfig.ClientAuth = options.ClientAuth tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) } return nil, fmt.Errorf("error reading X509 key pair - make sure the key is not encrypted (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) if err != nil { return nil, err } tlsConfig.ClientCAs = CAs } if err := adjustMinVersion(options, tlsConfig); err != nil { return nil, err } return tlsConfig, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/tlsconfig/certpool.go
vendor/github.com/docker/go-connections/tlsconfig/certpool.go
package tlsconfig import ( "crypto/x509" "runtime" ) // SystemCertPool returns a copy of the system cert pool, // returns an error if failed to load or empty pool on windows. func SystemCertPool() (*x509.CertPool, error) { certpool, err := x509.SystemCertPool() if err != nil && runtime.GOOS == "windows" { return x509.NewCertPool(), nil } return certpool, err }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/nat/nat.go
vendor/github.com/docker/go-connections/nat/nat.go
// Package nat is a convenience package for manipulation of strings describing network ports. package nat import ( "fmt" "net" "strconv" "strings" ) // PortBinding represents a binding between a Host IP address and a Host Port type PortBinding struct { // HostIP is the host IP Address HostIP string `json:"HostIp"` // HostPort is the host port number HostPort string } // PortMap is a collection of PortBinding indexed by Port type PortMap map[Port][]PortBinding // PortSet is a collection of structs indexed by Port type PortSet map[Port]struct{} // Port is a string containing port number and protocol in the format "80/tcp" type Port string // NewPort creates a new instance of a Port given a protocol and port number or port range func NewPort(proto, port string) (Port, error) { // Check for parsing issues on "port" now so we can avoid having // to check it later on. portStartInt, portEndInt, err := ParsePortRangeToInt(port) if err != nil { return "", err } if portStartInt == portEndInt { return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil } return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil } // ParsePort parses the port number string and returns an int func ParsePort(rawPort string) (int, error) { if len(rawPort) == 0 { return 0, nil } port, err := strconv.ParseUint(rawPort, 10, 16) if err != nil { return 0, err } return int(port), nil } // ParsePortRangeToInt parses the port range string and returns start/end ints func ParsePortRangeToInt(rawPort string) (int, int, error) { if len(rawPort) == 0 { return 0, 0, nil } start, end, err := ParsePortRange(rawPort) if err != nil { return 0, 0, err } return int(start), int(end), nil } // Proto returns the protocol of a Port func (p Port) Proto() string { proto, _ := SplitProtoPort(string(p)) return proto } // Port returns the port number of a Port func (p Port) Port() string { _, port := SplitProtoPort(string(p)) return port } // Int returns the port number of a Port as an int func (p Port) Int() int { portStr := p.Port() // We don't need to check for an error because we're going to // assume that any error would have been found, and reported, in NewPort() port, _ := ParsePort(portStr) return port } // Range returns the start/end port numbers of a Port range as ints func (p Port) Range() (int, int, error) { return ParsePortRangeToInt(p.Port()) } // SplitProtoPort splits a port in the format of proto/port func SplitProtoPort(rawPort string) (string, string) { parts := strings.Split(rawPort, "/") l := len(parts) if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 { return "", "" } if l == 1 { return "tcp", rawPort } if len(parts[1]) == 0 { return "tcp", parts[0] } return parts[1], parts[0] } func validateProto(proto string) bool { for _, availableProto := range []string{"tcp", "udp", "sctp"} { if availableProto == proto { return true } } return false } // ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses // these in to the internal types func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { var ( exposedPorts = make(map[Port]struct{}, len(ports)) bindings = make(map[Port][]PortBinding) ) for _, rawPort := range ports { portMappings, err := ParsePortSpec(rawPort) if err != nil { return nil, nil, err } for _, portMapping := range portMappings { port := portMapping.Port if _, exists := exposedPorts[port]; !exists { exposedPorts[port] = struct{}{} } bslice, exists := bindings[port] if !exists { bslice = []PortBinding{} } bindings[port] = append(bslice, portMapping.Binding) } } return exposedPorts, bindings, nil } // PortMapping is a data object mapping a Port to a PortBinding type PortMapping struct { Port Port Binding PortBinding } func splitParts(rawport string) (string, string, string) { parts := strings.Split(rawport, ":") n := len(parts) containerPort := parts[n-1] switch n { case 1: return "", "", containerPort case 2: return "", parts[0], containerPort case 3: return parts[0], parts[1], containerPort default: return strings.Join(parts[:n-2], ":"), parts[n-2], containerPort } } // ParsePortSpec parses a port specification string into a slice of PortMappings func ParsePortSpec(rawPort string) ([]PortMapping, error) { var proto string ip, hostPort, containerPort := splitParts(rawPort) proto, containerPort = SplitProtoPort(containerPort) if ip != "" && ip[0] == '[' { // Strip [] from IPV6 addresses rawIP, _, err := net.SplitHostPort(ip + ":") if err != nil { return nil, fmt.Errorf("invalid IP address %v: %w", ip, err) } ip = rawIP } if ip != "" && net.ParseIP(ip) == nil { return nil, fmt.Errorf("invalid IP address: %s", ip) } if containerPort == "" { return nil, fmt.Errorf("no port specified: %s<empty>", rawPort) } startPort, endPort, err := ParsePortRange(containerPort) if err != nil { return nil, fmt.Errorf("invalid containerPort: %s", containerPort) } var startHostPort, endHostPort uint64 = 0, 0 if len(hostPort) > 0 { startHostPort, endHostPort, err = ParsePortRange(hostPort) if err != nil { return nil, fmt.Errorf("invalid hostPort: %s", hostPort) } } if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { // Allow host port range iff containerPort is not a range. // In this case, use the host port range as the dynamic // host port range to allocate into. if endPort != startPort { return nil, fmt.Errorf("invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) } } if !validateProto(strings.ToLower(proto)) { return nil, fmt.Errorf("invalid proto: %s", proto) } ports := []PortMapping{} for i := uint64(0); i <= (endPort - startPort); i++ { containerPort = strconv.FormatUint(startPort+i, 10) if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } // Set hostPort to a range only if there is a single container port // and a dynamic host port. if startPort == endPort && startHostPort != endHostPort { hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) } port, err := NewPort(strings.ToLower(proto), containerPort) if err != nil { return nil, err } binding := PortBinding{ HostIP: ip, HostPort: hostPort, } ports = append(ports, PortMapping{Port: port, Binding: binding}) } return ports, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/nat/sort.go
vendor/github.com/docker/go-connections/nat/sort.go
package nat import ( "sort" "strings" ) type portSorter struct { ports []Port by func(i, j Port) bool } func (s *portSorter) Len() int { return len(s.ports) } func (s *portSorter) Swap(i, j int) { s.ports[i], s.ports[j] = s.ports[j], s.ports[i] } func (s *portSorter) Less(i, j int) bool { ip := s.ports[i] jp := s.ports[j] return s.by(ip, jp) } // Sort sorts a list of ports using the provided predicate // This function should compare `i` and `j`, returning true if `i` is // considered to be less than `j` func Sort(ports []Port, predicate func(i, j Port) bool) { s := &portSorter{ports, predicate} sort.Sort(s) } type portMapEntry struct { port Port binding PortBinding } type portMapSorter []portMapEntry func (s portMapSorter) Len() int { return len(s) } func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // Less sorts the port so that the order is: // 1. port with larger specified bindings // 2. larger port // 3. port with tcp protocol func (s portMapSorter) Less(i, j int) bool { pi, pj := s[i].port, s[j].port hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort) return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp") } // SortPortMap sorts the list of ports and their respected mapping. The ports // will explicit HostPort will be placed first. func SortPortMap(ports []Port, bindings PortMap) { s := portMapSorter{} for _, p := range ports { if binding, ok := bindings[p]; ok && len(binding) > 0 { for _, b := range binding { s = append(s, portMapEntry{port: p, binding: b}) } bindings[p] = []PortBinding{} } else { s = append(s, portMapEntry{port: p}) } } sort.Sort(s) var ( i int pm = make(map[Port]struct{}) ) // reorder ports for _, entry := range s { if _, ok := pm[entry.port]; !ok { ports[i] = entry.port pm[entry.port] = struct{}{} i++ } // reorder bindings for this port if _, ok := bindings[entry.port]; ok { bindings[entry.port] = append(bindings[entry.port], entry.binding) } } } func toInt(s string) uint64 { i, _, err := ParsePortRange(s) if err != nil { i = 0 } return i }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/go-connections/nat/parse.go
vendor/github.com/docker/go-connections/nat/parse.go
package nat import ( "fmt" "strconv" "strings" ) // ParsePortRange parses and validates the specified string as a port-range (8000-9000) func ParsePortRange(ports string) (uint64, uint64, error) { if ports == "" { return 0, 0, fmt.Errorf("empty string specified for ports") } if !strings.Contains(ports, "-") { start, err := strconv.ParseUint(ports, 10, 16) end := start return start, end, err } parts := strings.Split(ports, "-") start, err := strconv.ParseUint(parts[0], 10, 16) if err != nil { return 0, 0, err } end, err := strconv.ParseUint(parts[1], 10, 16) if err != nil { return 0, 0, err } if end < start { return 0, 0, fmt.Errorf("invalid range specified for port: %s", ports) } return start, end, nil }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/github.com/docker/docker/pkg/ioutils/readers.go
vendor/github.com/docker/docker/pkg/ioutils/readers.go
package ioutils import ( "context" "io" "runtime/debug" "sync/atomic" "github.com/containerd/log" ) // readCloserWrapper wraps an io.Reader, and implements an io.ReadCloser // It calls the given callback function when closed. It should be constructed // with NewReadCloserWrapper type readCloserWrapper struct { io.Reader closer func() error closed atomic.Bool } // Close calls back the passed closer function func (r *readCloserWrapper) Close() error { if !r.closed.CompareAndSwap(false, true) { subsequentCloseWarn("ReadCloserWrapper") return nil } return r.closer() } // NewReadCloserWrapper wraps an io.Reader, and implements an io.ReadCloser. // It calls the given callback function when closed. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { return &readCloserWrapper{ Reader: r, closer: closer, } } // cancelReadCloser wraps an io.ReadCloser with a context for cancelling read // operations. type cancelReadCloser struct { cancel func() pR *io.PipeReader // Stream to read from pW *io.PipeWriter closed atomic.Bool } // NewCancelReadCloser creates a wrapper that closes the ReadCloser when the // context is cancelled. The returned io.ReadCloser must be closed when it is // no longer needed. func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { pR, pW := io.Pipe() // Create a context used to signal when the pipe is closed doneCtx, cancel := context.WithCancel(context.Background()) p := &cancelReadCloser{ cancel: cancel, pR: pR, pW: pW, } go func() { _, err := io.Copy(pW, in) select { case <-ctx.Done(): // If the context was closed, p.closeWithError // was already called. Calling it again would // change the error that Read returns. default: p.closeWithError(err) } in.Close() }() go func() { for { select { case <-ctx.Done(): p.closeWithError(ctx.Err()) case <-doneCtx.Done(): return } } }() return p } // Read wraps the Read method of the pipe that provides data from the wrapped // ReadCloser. func (p *cancelReadCloser) Read(buf []byte) (int, error) { return p.pR.Read(buf) } // closeWithError closes the wrapper and its underlying reader. It will // cause future calls to Read to return err. func (p *cancelReadCloser) closeWithError(err error) { _ = p.pW.CloseWithError(err) p.cancel() } // Close closes the wrapper its underlying reader. It will cause // future calls to Read to return io.EOF. func (p *cancelReadCloser) Close() error { if !p.closed.CompareAndSwap(false, true) { subsequentCloseWarn("cancelReadCloser") return nil } p.closeWithError(io.EOF) return nil } func subsequentCloseWarn(name string) { log.G(context.TODO()).Error("subsequent attempt to close " + name) if log.GetLevel() >= log.DebugLevel { log.G(context.TODO()).Errorf("stack trace: %s", string(debug.Stack())) } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false