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/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/custom_commands/selected_path.go | pkg/integration/tests/custom_commands/selected_path.go | package custom_commands
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var SelectedPath = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Use the {{ .SelectedPath }} template variable in different contexts",
ExtraCmdArgs: []string{},
Skip: false,
SetupRepo: func(shell *Shell) {
shell.CreateDir("folder1")
shell.CreateFileAndAdd("folder1/file1", "")
shell.Commit("commit")
shell.CreateDir("folder2")
shell.CreateFile("folder2/file2", "")
},
SetupConfig: func(cfg *config.AppConfig) {
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "X",
Context: "global",
Command: "printf '%s' '{{ .SelectedPath }}' > file.txt",
},
}
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Files().
Focus().
NavigateToLine(Contains("file2"))
t.GlobalPress("X")
t.FileSystem().FileContent("file.txt", Equals("folder2/file2"))
t.Views().Commits().
Focus().
PressEnter()
t.Views().CommitFiles().
IsFocused().
NavigateToLine(Contains("file1"))
t.GlobalPress("X")
t.FileSystem().FileContent("file.txt", Equals("folder1/file1"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/custom_commands/selected_submodule.go | pkg/integration/tests/custom_commands/selected_submodule.go | package custom_commands
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var SelectedSubmodule = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Use the {{ .SelectedSubmodule }} template variable",
ExtraCmdArgs: []string{},
Skip: false,
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("Initial commit")
shell.CloneIntoSubmodule("submodule", "path/submodule")
shell.Commit("Add submodule")
},
SetupConfig: func(cfg *config.AppConfig) {
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "X",
Context: "submodules",
Command: "printf '%s' '{{ .SelectedSubmodule.Path }}' > file.txt",
},
{
Key: "U",
Context: "submodules",
Command: "printf '%s' '{{ .SelectedSubmodule.Url }}' > file.txt",
},
{
Key: "N",
Context: "submodules",
Command: "printf '%s' '{{ .SelectedSubmodule.Name }}' > file.txt",
},
}
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Submodules().
Focus().
Lines(
Contains("submodule").IsSelected(),
)
t.Views().Submodules().Press("X")
t.FileSystem().FileContent("file.txt", Equals("path/submodule"))
t.Views().Submodules().Press("U")
t.FileSystem().FileContent("file.txt", Equals("../submodule"))
t.Views().Submodules().Press("N")
t.FileSystem().FileContent("file.txt", Equals("submodule"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/custom_commands/custom_commands_submenu_with_special_keybindings.go | pkg/integration/tests/custom_commands/custom_commands_submenu_with_special_keybindings.go | package custom_commands
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var CustomCommandsSubmenuWithSpecialKeybindings = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Using custom commands from a custom commands menu with keybindings that conflict with builtin ones",
ExtraCmdArgs: []string{},
Skip: false,
SetupRepo: func(shell *Shell) {},
SetupConfig: func(cfg *config.AppConfig) {
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "x",
Description: "My Custom Commands",
CommandMenu: []config.CustomCommand{
{
Key: "j",
Context: "global",
Command: "echo j",
Output: "popup",
},
{
Key: "H",
Context: "global",
Command: "echo H",
Output: "popup",
},
{
Key: "y",
Context: "global",
Command: "echo y",
Output: "popup",
},
{
Key: "<down>",
Context: "global",
Command: "echo down",
Output: "popup",
},
},
},
}
cfg.GetUserConfig().Keybinding.Universal.ConfirmMenu = "y"
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Files().
Focus().
IsEmpty().
Press("x").
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("My Custom Commands")).
Lines(
Contains("j echo j"),
Contains("H echo H"),
Contains(" echo y"),
Contains(" echo down"),
)
t.GlobalPress("j")
t.ExpectPopup().Alert().Title(Equals("echo j")).Content(Equals("j")).Confirm()
}).
Press("x").
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("My Custom Commands"))
t.GlobalPress("H")
t.ExpectPopup().Alert().Title(Equals("echo H")).Content(Equals("H")).Confirm()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/custom_commands/selected_commit_range.go | pkg/integration/tests/custom_commands/selected_commit_range.go | package custom_commands
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var SelectedCommitRange = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Use the {{ .SelectedCommitRange }} template variable",
ExtraCmdArgs: []string{},
Skip: false,
SetupRepo: func(shell *Shell) {
shell.CreateNCommits(3)
},
SetupConfig: func(cfg *config.AppConfig) {
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "X",
Context: "global",
Command: `git log --format="%s" {{.SelectedCommitRange.From}}^..{{.SelectedCommitRange.To}} > file.txt`,
},
}
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().Focus().
Lines(
Contains("commit 03").IsSelected(),
Contains("commit 02"),
Contains("commit 01"),
)
t.GlobalPress("X")
t.FileSystem().FileContent("file.txt", Equals("commit 03\n"))
t.Views().Commits().Focus().
Press(keys.Universal.RangeSelectDown)
t.GlobalPress("X")
t.FileSystem().FileContent("file.txt", Equals("commit 03\ncommit 02\n"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/rebase_onto.go | pkg/integration/tests/demo/rebase_onto.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var RebaseOnto = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Rebase with '--onto' flag. We start with a feature branch on the develop branch that we want to rebase onto the master branch",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(60)
shell.NewBranch("develop")
shell.SetAuthor("Joe Blow", "joeblow@gmail.com")
shell.RandomChangeCommit("Develop commit 1")
shell.RandomChangeCommit("Develop commit 2")
shell.RandomChangeCommit("Develop commit 3")
shell.SetAuthor("Jesse Duffield", "jesseduffield@gmail.com")
shell.NewBranch("feature/demo")
shell.RandomChangeCommit("Feature commit 1")
shell.RandomChangeCommit("Feature commit 2")
shell.RandomChangeCommit("Feature commit 3")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("feature/demo", "origin/feature/demo")
shell.SetBranchUpstream("develop", "origin/develop")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Rebase from marked base commit")
t.Wait(1000)
// first we focus the commits view, then expand to show the branches against each commit
// Then we go back to normal value, mark the last develop branch commit as the marked commit
// Then go to the branches view and press 'r' on the master branch to rebase onto it
// then we force push our changes.
t.Views().Commits().
Focus().
Press(keys.Universal.PrevScreenMode).
Wait(500).
NavigateToLine(Contains("Develop commit 3")).
Wait(500).
Press(keys.Commits.MarkCommitAsBaseForRebase).
Wait(1000).
Press(keys.Universal.NextScreenMode).
Wait(500)
t.Views().Branches().
Focus().
Wait(500).
NavigateToLine(Contains("master")).
Wait(500).
Press(keys.Branches.RebaseBranch).
Tap(func() {
t.ExpectPopup().Menu().
Title(Contains("Rebase 'feature/demo' from marked base")).
Select(Contains("Simple rebase")).
Confirm()
}).
Wait(1000).
Press(keys.Universal.Push).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Contains("Force push")).
Content(AnyString()).
Wait(500).
Confirm()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/stage_lines.go | pkg/integration/tests/demo/stage_lines.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var originalFile = `# Lazygit
Simple terminal UI for git commands

## Installation
### Homebrew
`
var updatedFile = `# Lazygit
Simple terminal UI for git
(Not too simple though)

## Installation
### Homebrew
Just do brew install lazygit and bada bing bada
boom you have begun on the path of laziness.
`
var StageLines = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Stage individual lines",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
config.GetUserConfig().Gui.ShowFileTree = false
config.GetUserConfig().Gui.ShowCommandLog = false
},
SetupRepo: func(shell *Shell) {
shell.NewBranch("docs-fix")
shell.CreateNCommitsWithRandomMessages(30)
shell.CreateFileAndAdd("docs/README.md", originalFile)
shell.Commit("Update docs/README")
shell.UpdateFile("docs/README.md", updatedFile)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Stage individual lines")
t.Wait(1000)
t.Views().Files().
IsFocused().
PressEnter()
t.Views().Staging().
IsFocused().
Press(keys.Universal.ToggleRangeSelect).
PressFast(keys.Universal.NextItem).
PressFast(keys.Universal.NextItem).
Wait(500).
PressPrimaryAction().
Wait(500).
PressEscape()
t.Views().Files().
IsFocused().
Press(keys.Files.CommitChanges).
Tap(func() {
t.ExpectPopup().CommitMessagePanel().
Type("Update tagline").
Confirm()
})
t.Views().Commits().
Focus()
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/diff_commits.go | pkg/integration/tests/demo/diff_commits.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var DiffCommits = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Diff two commits",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
config.GetUserConfig().Gui.ShowFileTree = false
config.GetUserConfig().Gui.ShowCommandLog = false
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(50)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Compare two commits")
t.Wait(1000)
t.Views().Commits().
Focus().
NavigateToLine(Contains("Replace deprecated lifecycle methods in React components")).
Wait(1000).
Press(keys.Universal.DiffingMenu).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("Diffing")).
TopLines(
MatchesRegexp(`Diff .*`),
).
Wait(500).
Confirm()
}).
NavigateToLine(Contains("Move constants to a separate config file")).
Wait(1000).
PressEnter()
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/filter.go | pkg/integration/tests/demo/filter.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Filter = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Filter branches",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(30)
shell.NewBranch("feature/user-authentication")
shell.NewBranch("feature/payment-processing")
shell.NewBranch("feature/search-functionality")
shell.NewBranch("feature/mobile-responsive")
shell.NewBranch("bugfix/fix-login-issue")
shell.NewBranch("bugfix/fix-crash-bug")
shell.NewBranch("bugfix/fix-validation-error")
shell.NewBranch("refactor/improve-performance")
shell.NewBranch("refactor/code-cleanup")
shell.NewBranch("refactor/extract-method")
shell.NewBranch("docs/update-readme")
shell.NewBranch("docs/add-user-guide")
shell.NewBranch("docs/api-documentation")
shell.NewBranch("experiment/new-feature-idea")
shell.NewBranch("experiment/try-new-library")
shell.NewBranch("chore/update-dependencies")
shell.NewBranch("chore/add-test-cases")
shell.NewBranch("chore/migrate-database")
shell.NewBranch("hotfix/critical-bug")
shell.NewBranch("hotfix/security-patch")
shell.NewBranch("feature/social-media-integration")
shell.NewBranch("feature/email-notifications")
shell.NewBranch("feature/admin-panel")
shell.NewBranch("feature/analytics-dashboard")
shell.NewBranch("bugfix/fix-registration-flow")
shell.NewBranch("bugfix/fix-payment-bug")
shell.NewBranch("refactor/improve-error-handling")
shell.NewBranch("refactor/optimize-database-queries")
shell.NewBranch("docs/improve-tutorials")
shell.NewBranch("docs/add-faq-section")
shell.NewBranch("experiment/try-alternative-algorithm")
shell.NewBranch("experiment/implement-design-concept")
shell.NewBranch("chore/update-documentation")
shell.NewBranch("chore/improve-test-coverage")
shell.NewBranch("chore/cleanup-codebase")
shell.NewBranch("hotfix/critical-security-vulnerability")
shell.NewBranch("hotfix/fix-production-issue")
shell.NewBranch("feature/integrate-third-party-api")
shell.NewBranch("feature/image-upload-functionality")
shell.NewBranch("feature/localization-support")
shell.NewBranch("feature/chat-feature")
shell.NewBranch("bugfix/fix-broken-link")
shell.NewBranch("bugfix/fix-css-styling")
shell.NewBranch("refactor/improve-logging")
shell.NewBranch("refactor/extract-reusable-component")
shell.NewBranch("docs/add-changelog")
shell.NewBranch("docs/update-api-reference")
shell.NewBranch("experiment/implement-new-design")
shell.NewBranch("experiment/try-different-architecture")
shell.NewBranch("chore/clean-up-git-history")
shell.NewBranch("chore/update-environment-configuration")
shell.CreateFileAndAdd("env_config.rb", "EnvConfig.call(false)\n")
shell.Commit("Update env config")
shell.CreateFileAndAdd("env_config.rb", "# Turns out we need to pass true for this to work\nEnvConfig.call(true)\n")
shell.Commit("Fix env config issue")
shell.Checkout("docs/add-faq-section")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Fuzzy filter branches")
t.Wait(1000)
t.Views().Branches().
Focus().
Wait(500).
Press(keys.Universal.StartSearch).
Tap(func() {
t.Wait(500)
t.ExpectSearch().Type("environ").Confirm()
}).
Wait(500).
PressEnter()
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/undo.go | pkg/integration/tests/demo/undo.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Undo = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Undo",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(30)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Undo commands")
t.Wait(1000)
confirmCommitDrop := func() {
t.ExpectPopup().Confirmation().
Title(Equals("Drop commit")).
Content(Equals("Are you sure you want to drop the selected commit(s)?")).
Wait(500).
Confirm()
}
confirmUndo := func() {
t.ExpectPopup().Confirmation().
Title(Equals("Undo")).
Content(MatchesRegexp(`Are you sure you want to hard reset to '.*'\? An auto-stash will be performed if necessary\.`)).
Wait(500).
Confirm()
}
t.Views().Commits().Focus().
SetCaptionPrefix("Drop two commits").
Wait(1000).
Press(keys.Universal.Remove).
Tap(confirmCommitDrop).
Press(keys.Universal.Remove).
Tap(confirmCommitDrop).
SetCaptionPrefix("Undo the drops").
Wait(1000).
Press(keys.Universal.Undo).
Tap(confirmUndo).
Press(keys.Universal.Undo).
Tap(confirmUndo)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/custom_command.go | pkg/integration/tests/demo/custom_command.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var customCommandContent = `
customCommands:
- key: 'a'
command: 'git checkout {{.Form.Branch}}'
context: 'localBranches'
prompts:
- type: 'input'
title: 'Enter a branch name to checkout:'
key: 'Branch'
suggestions:
preset: 'branches'
`
var CustomCommand = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Invoke a custom command",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(cfg *config.AppConfig) {
setDefaultDemoConfig(cfg)
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "a",
Context: "localBranches",
Command: `git checkout {{.Form.Branch}}`,
Prompts: []config.CustomCommandPrompt{
{
Key: "Branch",
Type: "input",
Title: "Enter a branch name to checkout",
Suggestions: config.CustomCommandSuggestions{
Preset: "branches",
},
},
},
},
}
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(30)
shell.NewBranch("feature/user-authentication")
shell.NewBranch("feature/payment-processing")
shell.NewBranch("feature/search-functionality")
shell.NewBranch("feature/mobile-responsive")
shell.EmptyCommit("Make mobile response")
shell.NewBranch("bugfix/fix-login-issue")
shell.HardReset("HEAD~1")
shell.NewBranch("bugfix/fix-crash-bug")
shell.CreateFile("custom_commands_example.yml", customCommandContent)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Invoke a custom command")
t.Wait(1500)
t.Views().Branches().
Focus().
Wait(500).
Press("a").
Tap(func() {
t.Wait(500)
t.ExpectPopup().Prompt().
Title(Equals("Enter a branch name to checkout")).
Type("mobile").
ConfirmFirstSuggestion()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/custom_patch.go | pkg/integration/tests/demo/custom_patch.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var usersFileContent = `package main
import "fmt"
func main() {
// TODO: verify that this actually works
fmt.Println("hello world")
}
`
var CustomPatch = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Remove a line from an old commit",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(cfg *config.AppConfig) {
setDefaultDemoConfig(cfg)
cfg.GetUserConfig().Gui.UseHunkModeInStagingView = false
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(30)
shell.NewBranch("feature/user-authentication")
shell.EmptyCommit("Add user authentication feature")
shell.CreateFileAndAdd("src/users.go", "package main\n")
shell.Commit("Fix local session storage")
shell.CreateFile("src/authentication.go", "package main")
shell.CreateFile("src/session.go", "package main")
shell.UpdateFileAndAdd("src/users.go", usersFileContent)
shell.EmptyCommit("Stop using shims")
shell.UpdateFileAndAdd("src/authentication.go", "package authentication")
shell.UpdateFileAndAdd("src/session.go", "package session")
shell.Commit("Enhance user authentication feature")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Remove a line from an old commit")
t.Wait(1000)
t.Views().Commits().
Focus().
NavigateToLine(Contains("Stop using shims")).
Wait(1000).
PressEnter().
Tap(func() {
t.Views().CommitFiles().
IsFocused().
NavigateToLine(Contains("users.go")).
Wait(1000).
PressEnter().
Tap(func() {
t.Views().PatchBuilding().
IsFocused().
NavigateToLine(Contains("TODO")).
Wait(500).
PressPrimaryAction().
PressEscape()
}).
Press(keys.Universal.CreatePatchOptionsMenu).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("Patch options")).
Select(Contains("Remove patch from original commit")).
Wait(500).
Confirm()
}).
PressEscape()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/commit_and_push.go | pkg/integration/tests/demo/commit_and_push.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var CommitAndPush = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Make a commit and push",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateFile("my-file.txt", "myfile content")
shell.CreateFile("my-other-file.rb", "my-other-file content")
shell.CreateNCommitsWithRandomMessages(30)
shell.NewBranch("feature/demo")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("feature/demo", "origin/feature/demo")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Stage a file")
t.Wait(1000)
t.Views().Files().
IsFocused().
PressPrimaryAction().
SetCaptionPrefix("Commit our changes").
Press(keys.Files.CommitChanges)
t.ExpectPopup().CommitMessagePanel().
Type("my commit summary").
SwitchToDescription().
Type("my commit description").
SwitchToSummary().
Confirm()
t.Views().Commits().
TopLines(
Contains("my commit summary"),
)
t.SetCaptionPrefix("Push to the remote")
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/commit_graph.go | pkg/integration/tests/demo/commit_graph.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var CommitGraph = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Show commit graph",
ExtraCmdArgs: []string{"log", "--screen-mode=full"},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
setGeneratedAuthorColours(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateRepoHistory()
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("View commit log")
t.Wait(1000)
t.Views().Commits().
IsFocused().
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100).
SelectNextItem().
Wait(100)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/shared.go | pkg/integration/tests/demo/shared.go | package demo
import "github.com/jesseduffield/lazygit/pkg/config"
// Gives us nicer colours when we generate a git repo history with `shell.CreateRepoHistory()`
func setGeneratedAuthorColours(config *config.AppConfig) {
config.GetUserConfig().Gui.AuthorColors = map[string]string{
"Fredrica Greenhill": "#fb5aa3",
"Oscar Reuenthal": "#86c82f",
"Paul Oberstein": "#ffd500",
"Siegfried Kircheis": "#fe7e11",
"Yang Wen-li": "#8e3ccb",
}
}
func setDefaultDemoConfig(config *config.AppConfig) {
// demos look much nicer with icons shown
config.GetUserConfig().Gui.NerdFontsVersion = "3"
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/worktree_create_from_branches.go | pkg/integration/tests/demo/worktree_create_from_branches.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var WorktreeCreateFromBranches = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Create a worktree from the branches view",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(cfg *config.AppConfig) {
setDefaultDemoConfig(cfg)
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(30)
shell.NewBranch("feature/user-authentication")
shell.EmptyCommit("Add user authentication feature")
shell.EmptyCommit("Fix local session storage")
shell.CreateFile("src/authentication.go", "package main")
shell.CreateFile("src/shims.go", "package main")
shell.CreateFile("src/session.go", "package main")
shell.EmptyCommit("Stop using shims")
shell.UpdateFile("src/authentication.go", "package authentication")
shell.UpdateFileAndAdd("src/shims.go", "// removing for now")
shell.UpdateFile("src/session.go", "package session")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Create a worktree from a branch")
t.Wait(1000)
t.Views().Branches().
Focus().
NavigateToLine(Contains("master")).
Wait(500).
Press(keys.Worktrees.ViewWorktreeOptions).
Tap(func() {
t.Wait(500)
t.ExpectPopup().Menu().
Title(Equals("Worktree")).
Select(Contains("Create worktree from master").DoesNotContain("detached")).
Confirm()
t.ExpectPopup().Prompt().
Title(Equals("New worktree path")).
Type("../hotfix").
Confirm()
t.ExpectPopup().Prompt().
Title(Contains("New branch name")).
Type("hotfix/db-on-fire").
Confirm()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/nuke_working_tree.go | pkg/integration/tests/demo/nuke_working_tree.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var NukeWorkingTree = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Nuke the working tree",
ExtraCmdArgs: []string{"status", "--screen-mode=full"},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
config.GetUserConfig().Gui.AnimateExplosion = true
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("blah")
shell.CreateFile("controllers/red_controller.rb", "")
shell.CreateFile("controllers/green_controller.rb", "")
shell.CreateFileAndAdd("controllers/blue_controller.rb", "")
shell.CreateFile("controllers/README.md", "")
shell.CreateFileAndAdd("views/helpers/list.rb", "")
shell.CreateFile("views/helpers/sort.rb", "")
shell.CreateFileAndAdd("views/users_view.rb", "")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Nuke the working tree")
t.Wait(1000)
t.Views().Files().
IsFocused().
Wait(1000).
Press(keys.Files.ViewResetOptions).
Tap(func() {
t.Wait(1000)
t.ExpectPopup().Menu().
Title(Equals("")).
Select(Contains("Nuke working tree")).
Confirm()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/interactive_rebase.go | pkg/integration/tests/demo/interactive_rebase.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var InteractiveRebase = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Interactive rebase",
ExtraCmdArgs: []string{"log", "--screen-mode=full"},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateRepoHistory()
shell.NewBranch("feature/demo")
shell.CreateNCommitsWithRandomMessages(10)
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("feature/demo", "origin/feature/demo")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Interactive rebase")
t.Wait(1000)
t.Views().Commits().
IsFocused().
Press(keys.Commits.StartInteractiveRebase).
PressFast(keys.Universal.RangeSelectDown).
PressFast(keys.Universal.RangeSelectDown).
Press(keys.Commits.MarkCommitAsFixup).
PressFast(keys.Commits.MoveDownCommit).
PressFast(keys.Commits.MoveDownCommit).
Delay().
SelectNextItem().
SelectNextItem().
Press(keys.Universal.Remove).
SelectNextItem().
Press(keys.Commits.SquashDown).
Press(keys.Universal.CreateRebaseOptionsMenu).
Tap(func() {
t.ExpectPopup().Menu().
Title(Contains("Rebase options")).
Select(Contains("continue")).
Confirm()
}).
SetCaptionPrefix("Push to remote").
Press(keys.Universal.NextScreenMode).
Press(keys.Universal.Push).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Contains("Force push")).
Content(AnyString()).
Confirm()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/cherry_pick.go | pkg/integration/tests/demo/cherry_pick.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var CherryPick = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Cherry pick",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(50)
shell.
EmptyCommit("Fix bug in timezone conversion.").
NewBranch("hotfix/fix-bug").
NewBranch("feature/user-module").
Checkout("hotfix/fix-bug").
EmptyCommit("Integrate support for markdown in user posts").
EmptyCommit("Remove unused code and libraries").
Checkout("feature/user-module").
EmptyCommit("Handle session timeout gracefully").
EmptyCommit("Add Webpack for asset bundling").
Checkout("hotfix/fix-bug")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Cherry pick commits from another branch")
t.Wait(1000)
t.Views().Branches().
Focus().
Lines(
Contains("hotfix/fix-bug"),
Contains("feature/user-module"),
Contains("master"),
).
SelectNextItem().
Wait(300).
PressEnter()
t.Views().SubCommits().
IsFocused().
TopLines(
Contains("Add Webpack for asset bundling").IsSelected(),
Contains("Handle session timeout gracefully"),
Contains("Fix bug in timezone conversion."),
).
Press(keys.Commits.CherryPickCopy).
Tap(func() {
t.Views().Information().Content(Contains("1 commit copied"))
}).
SelectNextItem().
Press(keys.Commits.CherryPickCopy)
t.Views().Information().Content(Contains("2 commits copied"))
t.Views().Commits().
Focus().
TopLines(
Contains("Remove unused code and libraries").IsSelected(),
Contains("Integrate support for markdown in user posts"),
Contains("Fix bug in timezone conversion."),
).
Press(keys.Commits.PasteCommits).
Tap(func() {
t.Wait(1000)
t.ExpectPopup().Alert().
Title(Equals("Cherry-pick")).
Content(Contains("Are you sure you want to cherry-pick the 2 copied commit(s) onto this branch?")).
Confirm()
}).
TopLines(
Contains("Add Webpack for asset bundling"),
Contains("Handle session timeout gracefully"),
Contains("Remove unused code and libraries"),
Contains("Integrate support for markdown in user posts"),
Contains("Fix bug in timezone conversion."),
).
Tap(func() {
t.Views().Information().Content(DoesNotContain("commits copied"))
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/bisect.go | pkg/integration/tests/demo/bisect.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Bisect = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Interactive rebase",
ExtraCmdArgs: []string{"log", "--screen-mode=full"},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
},
SetupRepo: func(shell *Shell) {
shell.CreateFile("my-file.txt", "myfile content")
shell.CreateFile("my-other-file.rb", "my-other-file content")
shell.CreateNCommitsWithRandomMessages(60)
shell.NewBranch("feature/demo")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("feature/demo", "origin/feature/demo")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Git bisect")
t.Wait(1000)
markCommitAsBad := func() {
t.Views().Commits().
Press(keys.Commits.ViewBisectOptions)
t.ExpectPopup().Menu().Title(Equals("Bisect")).Select(MatchesRegexp(`Mark .* as bad`)).Confirm()
}
markCommitAsGood := func() {
t.Views().Commits().
Press(keys.Commits.ViewBisectOptions)
t.ExpectPopup().Menu().Title(Equals("Bisect")).Select(MatchesRegexp(`Mark .* as good`)).Confirm()
}
t.Views().Commits().
IsFocused().
Tap(func() {
markCommitAsBad()
t.Views().Information().Content(Contains("Bisecting"))
}).
SelectedLine(Contains("<-- bad")).
NavigateToLine(Contains("Add TypeScript types to User module")).
Tap(markCommitAsGood).
SelectedLine(Contains("Add loading indicators to improve UX").Contains("<-- current")).
Tap(markCommitAsBad).
SelectedLine(Contains("Fix broken links on the help page").Contains("<-- current")).
Tap(markCommitAsGood).
SelectedLine(Contains("Add end-to-end tests for checkout flow").Contains("<-- current")).
Tap(markCommitAsBad).
Tap(func() {
t.Wait(2000)
t.ExpectPopup().Alert().Title(Equals("Bisect complete")).Content(MatchesRegexp("(?s).*Do you want to reset")).Confirm()
}).
SetCaptionPrefix("Inspect problematic commit").
Wait(500).
Press(keys.Universal.PrevScreenMode).
IsFocused().
Content(Contains("Add end-to-end tests for checkout flow")).
Wait(500).
PressEnter()
t.Views().Information().Content(DoesNotContain("Bisecting"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/demo/amend_old_commit.go | pkg/integration/tests/demo/amend_old_commit.go | package demo
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var AmendOldCommit = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Amend old commit",
ExtraCmdArgs: []string{},
Skip: false,
IsDemo: true,
SetupConfig: func(config *config.AppConfig) {
setDefaultDemoConfig(config)
config.GetUserConfig().Gui.ShowFileTree = false
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommitsWithRandomMessages(60)
shell.NewBranch("feature/demo")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("feature/demo", "origin/feature/demo")
shell.UpdateFile("navigation/site_navigation.go", "package navigation\n\nfunc Navigate() {\n\tpanic(\"unimplemented\")\n}")
shell.CreateFile("docs/README.md", "my readme content")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.SetCaptionPrefix("Amend an old commit")
t.Wait(1000)
t.Views().Files().
IsFocused().
SelectedLine(Contains("site_navigation.go")).
PressPrimaryAction()
t.Views().Commits().
Focus().
NavigateToLine(Contains("Improve accessibility of site navigation")).
Wait(500).
Press(keys.Commits.AmendToCommit).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Equals("Amend commit")).
Wait(1000).
Content(AnyString()).
Confirm()
t.Wait(1000)
}).
Press(keys.Universal.Push).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Equals("Force push")).
Content(AnyString()).
Wait(1000).
Confirm()
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/reset.go | pkg/integration/tests/submodule/reset.go | package submodule
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Reset = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Enter a submodule, create a commit and stage some changes, then reset the submodule from back in the parent repo. This test captures functionality around getting a dirty submodule out of your files panel.",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "e",
Context: "files",
Command: "git commit --allow-empty -m \"empty commit\" && echo \"my_file content\" > my_file",
},
}
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.CloneIntoSubmodule("my_submodule_name", "my_submodule_path")
shell.GitAddAll()
shell.Commit("add submodule")
shell.CreateFile("other_file", "")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
assertInParentRepo := func() {
t.Views().Status().Content(Contains("repo"))
}
assertInSubmodule := func() {
t.Views().Status().Content(Contains("my_submodule_path(my_submodule_name)"))
}
assertInParentRepo()
t.Views().Submodules().Focus().
Lines(
Contains("my_submodule_name").IsSelected(),
).
// enter the submodule
PressEnter()
assertInSubmodule()
t.Views().Files().IsFocused().
Press("e").
Tap(func() {
t.Views().Commits().Content(Contains("empty commit"))
t.Views().Files().Content(Contains("my_file"))
}).
Lines(
Contains("my_file").IsSelected(),
).
// stage my_file
PressPrimaryAction().
// return to the parent repo
PressEscape()
assertInParentRepo()
t.Views().Submodules().IsFocused()
t.Views().Main().Content(Contains("Submodule my_submodule_path contains modified content"))
t.Views().Files().Focus().
Lines(
Equals("▼ /"),
Equals(" M my_submodule_path (submodule)"),
Equals(" ?? other_file").IsSelected(),
).
// Verify we can't reset a submodule and file change at the same time.
Press(keys.Universal.ToggleRangeSelect).
SelectPreviousItem().
Lines(
Equals("▼ /"),
Equals(" M my_submodule_path (submodule)").IsSelected(),
Equals(" ?? other_file").IsSelected(),
).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectToast(Contains("Disabled: Multiselection not supported for submodules"))
}).
Press(keys.Universal.ToggleRangeSelect).
Lines(
Equals("▼ /"),
Equals(" M my_submodule_path (submodule)").IsSelected(),
Equals(" ?? other_file"),
).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("my_submodule_path")).
Select(Contains("Stash uncommitted submodule changes and update")).
Confirm()
}).
Lines(
Equals("?? other_file").IsSelected(),
)
t.Views().Submodules().Focus().
PressEnter()
assertInSubmodule()
// submodule has been hard reset to the commit the parent repo specifies
t.Views().Branches().Lines(
Contains("HEAD detached"),
Contains("master").IsSelected(),
)
// empty commit is gone
t.Views().Commits().Lines(
Contains("first commit").IsSelected(),
)
// the staged change has been stashed
t.Views().Files().IsEmpty()
t.Views().Stash().Focus().
Lines(
Contains("WIP on master").IsSelected(),
)
t.Views().Main().Content(Contains("my_file content"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/enter_nested.go | pkg/integration/tests/submodule/enter_nested.go | package submodule
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var EnterNested = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Enter a nested submodule",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
setupNestedSubmodules(shell)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Submodules().Focus().
Lines(
Equals("outerSubName").IsSelected(),
Equals(" - innerSubName"),
).
Tap(func() {
t.Views().Main().ContainsLines(
Contains("Name: outerSubName"),
Contains("Path: modules/outerSubPath"),
Contains("Url: ../outerSubmodule"),
)
}).
SelectNextItem().
Tap(func() {
t.Views().Main().ContainsLines(
Contains("Name: outerSubName/innerSubName"),
Contains("Path: modules/outerSubPath/modules/innerSubPath"),
Contains("Url: ../innerSubmodule"),
)
}).
// enter the nested submodule
PressEnter()
t.Views().Status().Content(Contains("innerSubPath(innerSubName)"))
t.Views().Commits().ContainsLines(
Contains("initial inner commit"),
)
t.Views().Files().PressEscape()
t.Views().Status().Content(Contains("repo"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/remove_nested.go | pkg/integration/tests/submodule/remove_nested.go | package submodule
import (
"path/filepath"
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var RemoveNested = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Remove a nested submodule",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
setupNestedSubmodules(shell)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
gitDirSubmodulePath, _ := filepath.Abs(".git/modules/outerSubName/modules/innerSubName")
t.FileSystem().PathPresent(gitDirSubmodulePath)
t.Views().Submodules().Focus().
Lines(
Equals("outerSubName").IsSelected(),
Equals(" - innerSubName"),
).
SelectNextItem().
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Equals("Remove submodule")).
Content(Equals("Are you sure you want to remove submodule 'outerSubName/innerSubName' and its corresponding directory? This is irreversible.")).
Confirm()
}).
Lines(
Equals("outerSubName").IsSelected(),
).
Press(keys.Universal.GoInto)
t.Views().Files().IsFocused().
Lines(
Equals("▼ /").IsSelected(),
Equals(" ▼ modules"),
Equals(" D innerSubPath"),
Equals(" M .gitmodules"),
).
NavigateToLine(Contains(".gitmodules"))
t.Views().Main().Content(
Contains("-[submodule \"innerSubName\"]").
Contains("- path = modules/innerSubPath").
Contains("- url = ../innerSubmodule"),
)
t.FileSystem().PathNotPresent(gitDirSubmodulePath)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/add.go | pkg/integration/tests/submodule/add.go | package submodule
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Add = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Add a submodule",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.Clone("other_repo")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Submodules().Focus().
Press(keys.Universal.New).
Tap(func() {
t.ExpectPopup().Prompt().
Title(Equals("New submodule URL:")).
Type("../other_repo").Confirm()
t.ExpectPopup().Prompt().
Title(Equals("New submodule name:")).
InitialText(Equals("other_repo")).
Clear().Type("my_submodule").Confirm()
t.ExpectPopup().Prompt().
Title(Equals("New submodule path:")).
InitialText(Equals("my_submodule")).
Clear().Type("my_submodule_path").Confirm()
}).
Lines(
Contains("my_submodule").IsSelected(),
)
t.Views().Main().TopLines(
Contains("Name: my_submodule"),
Contains("Path: my_submodule_path"),
Contains("Url: ../other_repo"),
)
t.Views().Files().Focus().
Lines(
Equals("▼ /").IsSelected(),
Equals(" A .gitmodules"),
Equals(" A my_submodule_path (submodule)"),
).
SelectNextItem().
Tap(func() {
t.Views().Main().Content(
Contains("[submodule \"my_submodule\"]").
Contains("path = my_submodule_path").
Contains("url = ../other_repo"),
)
}).
SelectNextItem().
Tap(func() {
t.Views().Main().Content(
Contains("Submodule my_submodule_path").
Contains("(new submodule)"),
)
})
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/shared.go | pkg/integration/tests/submodule/shared.go | package submodule
import (
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
func setupNestedSubmodules(shell *Shell) {
// we're going to have a directory structure like this:
// project
// - repo/modules/outerSubName/modules/innerSubName/
//
shell.CreateFileAndAdd("rootFile", "rootStuff")
shell.Commit("initial repo commit")
shell.Chdir("..")
shell.CreateDir("innerSubmodule")
shell.Chdir("innerSubmodule")
shell.Init()
shell.CreateFileAndAdd("inner", "inner")
shell.Commit("initial inner commit")
shell.Chdir("..")
shell.CreateDir("outerSubmodule")
shell.Chdir("outerSubmodule")
shell.Init()
shell.CreateFileAndAdd("outer", "outer")
shell.Commit("initial outer commit")
shell.CreateDir("modules")
// the git config (-c) parameter below is required
// to let git create a file-protocol/path submodule
shell.RunCommand([]string{"git", "-c", "protocol.file.allow=always", "submodule", "add", "--name", "innerSubName", "../innerSubmodule", "modules/innerSubPath"})
shell.Commit("add dependency as innerSubmodule")
shell.Chdir("../repo")
shell.CreateDir("modules")
shell.RunCommand([]string{"git", "-c", "protocol.file.allow=always", "submodule", "add", "--name", "outerSubName", "../outerSubmodule", "modules/outerSubPath"})
shell.Commit("add dependency as outerSubmodule")
shell.RunCommand([]string{"git", "-c", "protocol.file.allow=always", "submodule", "update", "--init", "--recursive"})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/remove.go | pkg/integration/tests/submodule/remove.go | package submodule
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Remove = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Remove a submodule",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.CloneIntoSubmodule("my_submodule_name", "my_submodule_path")
shell.GitAddAll()
shell.Commit("add submodule")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
gitDirSubmodulePath := ".git/modules/my_submodule_name"
t.FileSystem().PathPresent(gitDirSubmodulePath)
t.Views().Submodules().Focus().
Lines(
Contains("my_submodule_name").IsSelected(),
).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Equals("Remove submodule")).
Content(Equals("Are you sure you want to remove submodule 'my_submodule_name' and its corresponding directory? This is irreversible.")).
Confirm()
}).
IsEmpty()
t.Views().Files().Focus().
Lines(
Equals("▼ /").IsSelected(),
Equals(" M .gitmodules"),
Equals(" D my_submodule_path"),
).
SelectNextItem()
t.Views().Main().Content(
Contains("-[submodule \"my_submodule_name\"]").
Contains("- path = my_submodule_path").
Contains("- url = ../my_submodule_name"),
)
t.FileSystem().PathNotPresent(gitDirSubmodulePath)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/reset_folder.go | pkg/integration/tests/submodule/reset_folder.go | package submodule
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var ResetFolder = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Reset submodule changes located in a nested folder.",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.CreateDir("dir")
shell.CloneIntoSubmodule("submodule1", "dir/submodule1")
shell.CloneIntoSubmodule("submodule2", "dir/submodule2")
shell.GitAddAll()
shell.Commit("add submodules")
shell.CreateFile("dir/submodule1/file", "")
shell.CreateFile("dir/submodule2/file", "")
shell.CreateFile("dir/file", "")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Files().Focus().
Lines(
Equals("▼ dir").IsSelected(),
Equals(" ?? file"),
Equals(" M submodule1 (submodule)"),
Equals(" M submodule2 (submodule)"),
).
// Verify we cannot reset the entire folder (has nested file and submodule changes).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectToast(Contains("Disabled: Multiselection not supported for submodules"))
}).
// Verify we cannot reset submodule + file or submodule + submodule via range select.
SelectNextItem().
Press(keys.Universal.ToggleRangeSelect).
SelectNextItem().
Lines(
Equals("▼ dir"),
Equals(" ?? file").IsSelected(),
Equals(" M submodule1 (submodule)").IsSelected(),
Equals(" M submodule2 (submodule)"),
).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectToast(Contains("Disabled: Multiselection not supported for submodules"))
}).
Press(keys.Universal.ToggleRangeSelect).
Press(keys.Universal.ToggleRangeSelect).
SelectNextItem().
Lines(
Equals("▼ dir"),
Equals(" ?? file"),
Equals(" M submodule1 (submodule)").IsSelected(),
Equals(" M submodule2 (submodule)").IsSelected(),
).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectToast(Contains("Disabled: Multiselection not supported for submodules"))
}).
// Reset the file change.
Press(keys.Universal.ToggleRangeSelect).
NavigateToLine(Contains("file")).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("Discard changes")).
Select(Contains("Discard all changes")).
Confirm()
}).
NavigateToLine(Contains("▼ dir")).
Lines(
Equals("▼ dir").IsSelected(),
Equals(" M submodule1 (submodule)"),
Equals(" M submodule2 (submodule)"),
).
// Verify we still cannot reset the entire folder (has two submodule changes).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectToast(Contains("Disabled: Multiselection not supported for submodules"))
}).
// Reset one of the submodule changes.
SelectNextItem().
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("dir/submodule1")).
Select(Contains("Stash uncommitted submodule changes and update")).
Confirm()
}).
NavigateToLine(Contains("▼ dir")).
Lines(
Equals("▼ dir").IsSelected(),
Equals(" M submodule2 (submodule)"),
).
// Now we can reset the folder (equivalent to resetting just the nested submodule change).
// Range selecting both the folder and submodule change is allowed.
Press(keys.Universal.ToggleRangeSelect).
SelectNextItem().
Lines(
Equals("▼ dir").IsSelected(),
Equals(" M submodule2 (submodule)").IsSelected(),
).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("dir/submodule2")).
Select(Contains("Stash uncommitted submodule changes and update")).
Cancel()
}).
// Or just selecting the folder itself.
NavigateToLine(Contains("▼ dir")).
Press(keys.Universal.Remove).
Tap(func() {
t.ExpectPopup().Menu().
Title(Equals("dir/submodule2")).
Select(Contains("Stash uncommitted submodule changes and update")).
Confirm()
}).
IsEmpty()
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/submodule/enter.go | pkg/integration/tests/submodule/enter.go | package submodule
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Enter = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Enter a submodule, add a commit, and then stage the change in the parent repo",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(cfg *config.AppConfig) {
cfg.GetUserConfig().CustomCommands = []config.CustomCommand{
{
Key: "e",
Context: "files",
Command: "git commit --allow-empty -m \"empty commit\"",
},
}
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("first commit")
shell.CloneIntoSubmodule("my_submodule_name", "my_submodule_path")
shell.GitAddAll()
shell.Commit("add submodule")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
assertInParentRepo := func() {
t.Views().Status().Content(Contains("repo"))
}
assertInSubmodule := func() {
t.Views().Status().Content(Contains("my_submodule_path(my_submodule_name)"))
}
assertInParentRepo()
t.Views().Submodules().Focus().
Lines(
Contains("my_submodule_name").IsSelected(),
).
// enter the submodule
PressEnter()
assertInSubmodule()
t.Views().Files().IsFocused().
Press("e").
Tap(func() {
t.Views().Commits().Content(Contains("empty commit"))
}).
// return to the parent repo
PressEscape()
assertInParentRepo()
t.Views().Submodules().IsFocused()
// we see the new commit in the submodule is ready to be staged in the parent repo
t.Views().Main().Content(Contains("> empty commit"))
t.Views().Files().Focus().
Lines(
MatchesRegexp(` M.*my_submodule_path \(submodule\)`).IsSelected(),
).
Tap(func() {
// main view also shows the new commit when we're looking at the submodule within the files view
t.Views().Main().Content(Contains("> empty commit"))
}).
PressPrimaryAction().
Press(keys.Files.CommitChanges).
Tap(func() {
t.ExpectPopup().CommitMessagePanel().Type("submodule change").Confirm()
}).
IsEmpty()
t.Views().Submodules().Focus()
// we no longer report a new commit because we've committed it in the parent repo
t.Views().Main().Content(DoesNotContain("> empty commit"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/fetch_and_auto_forward_branches_all_branches.go | pkg/integration/tests/sync/fetch_and_auto_forward_branches_all_branches.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var FetchAndAutoForwardBranchesAllBranches = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Fetch from remote and auto-forward branches with config set to 'allBranches'",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
config.GetUserConfig().Git.AutoForwardBranches = "allBranches"
config.GetUserConfig().Git.LocalBranchSortOrder = "alphabetical"
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommits(3)
shell.NewBranch("feature")
shell.NewBranch("diverged")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.SetBranchUpstream("feature", "origin/feature")
shell.SetBranchUpstream("diverged", "origin/diverged")
shell.Checkout("master")
shell.HardReset("HEAD^")
shell.Checkout("feature")
shell.HardReset("HEAD~2")
shell.Checkout("diverged")
shell.HardReset("HEAD~2")
shell.EmptyCommit("local")
shell.NewBranch("checked-out")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ↓2").DoesNotContain("↑"),
Contains("master ↓1").DoesNotContain("↑"),
)
t.Views().Files().
IsFocused().
Press(keys.Files.Fetch)
// AutoForwardBranches is "allBranches": both master and feature get forwarded
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ✓"),
Contains("master ✓"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_and_set_upstream.go | pkg/integration/tests/sync/pull_and_set_upstream.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullAndSetUpstream = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull a commit from the remote, setting the upstream branch in the process",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.CloneIntoRemote("origin")
// remove the 'two' commit so that we have something to pull from the remote
shell.HardReset("HEAD^")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("repo → master"))
t.Views().Files().IsFocused().Press(keys.Universal.Pull)
t.ExpectPopup().Prompt().
Title(Equals("Enter upstream as '<remote> <branchname>'")).
SuggestionLines(Equals("origin master")).
ConfirmFirstSuggestion()
t.Views().Commits().
Lines(
Contains("two"),
Contains("one"),
)
t.Views().Status().Content(Equals("✓ repo → master"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/fetch_when_sorted_by_date.go | pkg/integration/tests/sync/fetch_when_sorted_by_date.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var FetchWhenSortedByDate = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Fetch a branch while sort order is by date; verify that branch stays selected",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.
EmptyCommitWithDate("commit", "2023-04-07 10:00:00"). // first master commit, older than branch2
EmptyCommitWithDate("commit", "2023-04-07 12:00:00"). // second master commit, newer than branch2
NewBranch("branch1"). // branch1 will be checked out, so its date doesn't matter
EmptyCommitWithDate("commit", "2023-04-07 11:00:00"). // branch2 commit, date is between the two master commits
NewBranch("branch2").
Checkout("master").
CloneIntoRemote("origin").
SetBranchUpstream("master", "origin/master"). // upstream points to second master commit
HardReset("HEAD^"). // rewind to first master commit
Checkout("branch1")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Branches().
Focus().
Press(keys.Branches.SortOrder)
t.ExpectPopup().Menu().Title(Equals("Sort order")).
Select(Contains("-committerdate")).
Confirm()
t.Views().Branches().
Lines(
Contains("* branch1").IsSelected(),
Contains("branch2"),
Contains("master ↓1"),
).
NavigateToLine(Contains("master")).
Press(keys.Branches.FetchRemote).
Lines(
Contains("* branch1"),
Contains("master").IsSelected(),
Contains("branch2"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_rebase_conflict.go | pkg/integration/tests/sync/pull_rebase_conflict.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullRebaseConflict = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull with a rebase strategy, where a conflict occurs",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file", "content1")
shell.Commit("one")
shell.UpdateFileAndAdd("file", "content2")
shell.Commit("two")
shell.EmptyCommit("three")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.HardReset("HEAD^^")
shell.UpdateFileAndAdd("file", "content4")
shell.Commit("four")
shell.SetConfig("pull.rebase", "true")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("four"),
Contains("one"),
)
t.Views().Status().Content(Equals("↓2↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Pull)
t.Common().AcknowledgeConflicts()
t.Views().Files().
IsFocused().
Lines(
Contains("UU").Contains("file"),
).
PressEnter()
t.Views().MergeConflicts().
IsFocused().
TopLines(
Contains("<<<<<<< HEAD"),
Contains("content2"),
Contains("======="),
Contains("content4"),
Contains(">>>>>>>"),
).
SelectNextItem().
PressPrimaryAction() // choose 'content4'
t.Common().ContinueOnConflictsResolved("rebase")
t.Views().Status().Content(Equals("↑1 repo → master"))
t.Views().Commits().
Focus().
Lines(
Contains("four").IsSelected(),
Contains("three"),
Contains("two"),
Contains("one"),
)
t.Views().Main().
Content(
Contains("-content2").
Contains("+content4"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_rebase.go | pkg/integration/tests/sync/pull_rebase.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullRebase = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull with a rebase strategy",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file", "content1")
shell.Commit("one")
shell.UpdateFileAndAdd("file", "content2")
shell.Commit("two")
shell.CreateFileAndAdd("file3", "content3")
shell.Commit("three")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.HardReset("HEAD^^")
shell.CreateFileAndAdd("file4", "content4")
shell.Commit("four")
shell.SetConfig("pull.rebase", "true")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("four"),
Contains("one"),
)
t.Views().Status().Content(Equals("↓2↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Pull)
t.Views().Status().Content(Equals("↑1 repo → master"))
t.Views().Commits().
Lines(
Contains("four"),
Contains("three"),
Contains("two"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/force_push_triangular.go | pkg/integration/tests/sync/force_push_triangular.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var ForcePushTriangular = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push to a remote, requiring a force push because the branch is behind the remote push branch but not the upstream",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.SetConfig("push.default", "current")
shell.EmptyCommit("one")
shell.CloneIntoRemote("origin")
shell.NewBranch("feature")
shell.SetBranchUpstream("feature", "origin/master")
shell.EmptyCommit("two")
shell.PushBranch("origin", "feature")
// remove the 'two' commit so that we are behind the push branch
shell.HardReset("HEAD^")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Contains("✓ repo → feature"))
t.Views().Files().IsFocused().Press(keys.Universal.Push)
t.ExpectPopup().Confirmation().
Title(Equals("Force push")).
Content(Equals("Your branch has diverged from the remote branch. Press <esc> to cancel, or <enter> to force push.")).
Confirm()
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Contains("✓ repo → feature"))
t.Views().Remotes().Focus().
Lines(Contains("origin")).
PressEnter()
t.Views().RemoteBranches().IsFocused().
Lines(
Contains("feature"),
Contains("master"),
).
PressEnter()
t.Views().SubCommits().IsFocused().
Lines(Contains("one"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push_with_credential_prompt.go | pkg/integration/tests/sync/push_with_credential_prompt.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PushWithCredentialPrompt = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push a commit to a pre-configured upstream, where credentials are required",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.EmptyCommit("two")
// actually getting a password prompt is tricky: it requires SSH'ing into localhost under a newly created, restricted, user.
// This is not easy to do in a cross-platform way, nor is it easy to do in a docker container.
// If you can think of a way to do it, please let me know!
shell.CopyHelpFile("pre-push", ".git/hooks/pre-push")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Status().Content(Equals("↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
// correct credentials are: username=username, password=password
t.ExpectPopup().Prompt().
Title(Equals("Username")).
Type("username").
Confirm()
// enter incorrect password
t.ExpectPopup().Prompt().
Title(Equals("Password")).
Type("incorrect password").
Confirm()
t.ExpectPopup().Alert().
Title(Equals("Error")).
Content(Contains("incorrect username/password")).
Confirm()
t.Views().Status().Content(Equals("↑1 repo → master"))
// try again with correct password
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
t.ExpectPopup().Prompt().
Title(Equals("Username")).
Type("username").
Confirm()
t.ExpectPopup().Prompt().
Title(Equals("Password")).
Type("password").
Confirm()
t.Views().Status().Content(Equals("✓ repo → master"))
assertSuccessfullyPushed(t)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/fetch_prune.go | pkg/integration/tests/sync/fetch_prune.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var FetchPrune = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Fetch from the remote with the 'prune' option set in the git config",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
// This option makes it so that git checks for deleted branches in the remote
// upon fetching.
shell.SetConfig("fetch.prune", "true")
shell.EmptyCommit("my commit message")
shell.NewBranch("branch_to_remove")
shell.Checkout("master")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.SetBranchUpstream("branch_to_remove", "origin/branch_to_remove")
// # unbeknownst to our test repo we're removing the branch on the remote, so upon
// # fetching with prune: true we expect git to realise the remote branch is gone
shell.RemoveRemoteBranch("origin", "branch_to_remove")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Branches().
Lines(
Contains("master"),
Contains("branch_to_remove").DoesNotContain("upstream gone"),
)
t.Views().Files().
IsFocused().
Press(keys.Files.Fetch)
t.Views().Branches().
Lines(
Contains("master"),
Contains("branch_to_remove").Contains("upstream gone"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_rebase_interactive_conflict_drop.go | pkg/integration/tests/sync/pull_rebase_interactive_conflict_drop.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullRebaseInteractiveConflictDrop = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull with an interactive rebase strategy, where a conflict occurs. Also drop a commit while rebasing",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file", "content1")
shell.Commit("one")
shell.UpdateFileAndAdd("file", "content2")
shell.Commit("two")
shell.CreateFileAndAdd("file3", "content3")
shell.Commit("three")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.HardReset("HEAD^^")
shell.UpdateFileAndAdd("file", "content4")
shell.Commit("four")
shell.CreateFileAndAdd("fil5", "content5")
shell.Commit("five")
shell.SetConfig("pull.rebase", "interactive")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("five"),
Contains("four"),
Contains("one"),
)
t.Views().Status().Content(Equals("↓2↑2 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Pull)
t.Common().AcknowledgeConflicts()
t.Views().Commits().
Focus().
Lines(
Contains("--- Pending rebase todos ---"),
Contains("pick").Contains("five").IsSelected(),
Contains("pick").Contains("CONFLICT").Contains("four"),
Contains("--- Commits ---"),
Contains("three"),
Contains("two"),
Contains("one"),
).
Press(keys.Universal.Remove).
Lines(
Contains("--- Pending rebase todos ---"),
Contains("drop").Contains("five").IsSelected(),
Contains("pick").Contains("CONFLICT").Contains("four"),
Contains("--- Commits ---"),
Contains("three"),
Contains("two"),
Contains("one"),
)
t.Views().Files().
Focus().
Lines(
Contains("UU").Contains("file"),
).
PressEnter()
t.Views().MergeConflicts().
IsFocused().
TopLines(
Contains("<<<<<<< HEAD"),
Contains("content2"),
Contains("======="),
Contains("content4"),
Contains(">>>>>>>"),
).
SelectNextItem().
PressPrimaryAction() // choose 'content4'
t.Common().ContinueOnConflictsResolved("rebase")
t.Views().Status().Content(Equals("↑1 repo → master"))
t.Views().Commits().
Focus().
Lines(
Contains("four").IsSelected(),
Contains("three"),
Contains("two"),
Contains("one"),
)
t.Views().Main().
Content(
Contains("-content2").
Contains("+content4"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_merge_conflict.go | pkg/integration/tests/sync/pull_merge_conflict.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullMergeConflict = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull with a merge strategy, where a conflict occurs",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file", "content1")
shell.Commit("one")
shell.UpdateFileAndAdd("file", "content2")
shell.Commit("two")
shell.EmptyCommit("three")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.HardReset("HEAD^^")
shell.UpdateFileAndAdd("file", "content4")
shell.Commit("four")
shell.SetConfig("pull.rebase", "false")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("four"),
Contains("one"),
)
t.Views().Status().Content(Equals("↓2↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Pull)
t.Common().AcknowledgeConflicts()
t.Views().Files().
IsFocused().
Lines(
Contains("UU").Contains("file"),
).
PressEnter()
t.Views().MergeConflicts().
IsFocused().
TopLines(
Contains("<<<<<<< HEAD"),
Contains("content4"),
Contains("======="),
Contains("content2"),
Contains(">>>>>>>"),
).
PressPrimaryAction() // choose 'content4'
t.Common().ContinueOnConflictsResolved("merge")
t.Views().Status().Content(Equals("↑2 repo → master"))
t.Views().Commits().
Focus().
Lines(
Contains("Merge branch 'master' of ../origin").IsSelected(),
Contains("three"),
Contains("two"),
Contains("four"),
Contains("one"),
)
t.Views().Main().
Content(
Contains("- content4").
Contains(" -content2").
Contains("++content4"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push_and_auto_set_upstream.go | pkg/integration/tests/sync/push_and_auto_set_upstream.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PushAndAutoSetUpstream = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push a commit and set the upstream automatically as configured by git",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.CloneIntoRemote("origin")
shell.EmptyCommit("two")
shell.SetConfig("push.default", "current")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
// assert no mention of upstream/downstream changes
t.Views().Status().Content(Equals("repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
assertSuccessfullyPushed(t)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/fetch_and_auto_forward_branches_only_main_branches.go | pkg/integration/tests/sync/fetch_and_auto_forward_branches_only_main_branches.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var FetchAndAutoForwardBranchesOnlyMainBranches = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Fetch from remote and auto-forward branches with config set to 'onlyMainBranches'",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
config.GetUserConfig().Git.AutoForwardBranches = "onlyMainBranches"
config.GetUserConfig().Git.LocalBranchSortOrder = "alphabetical"
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommits(3)
shell.NewBranch("feature")
shell.NewBranch("diverged")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.SetBranchUpstream("feature", "origin/feature")
shell.SetBranchUpstream("diverged", "origin/diverged")
shell.Checkout("master")
shell.HardReset("HEAD^")
shell.Checkout("feature")
shell.HardReset("HEAD~2")
shell.Checkout("diverged")
shell.HardReset("HEAD~2")
shell.EmptyCommit("local")
shell.NewBranch("checked-out")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ↓2").DoesNotContain("↑"),
Contains("master ↓1").DoesNotContain("↑"),
)
t.Views().Files().
IsFocused().
Press(keys.Files.Fetch)
// AutoForwardBranches is "onlyMainBranches": master gets forwarded, but feature doesn't
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ↓2").DoesNotContain("↑"),
Contains("master ✓"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/rename_branch_and_pull.go | pkg/integration/tests/sync/rename_branch_and_pull.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var RenameBranchAndPull = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Rename a branch to no longer match its upstream, then pull from the upstream",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
// remove the 'two' commit so that we have something to pull from the remote
shell.HardReset("HEAD^")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Branches().
Focus().
Lines(
Contains("master"),
).
Press(keys.Branches.RenameBranch).
Tap(func() {
t.ExpectPopup().Confirmation().
Title(Equals("Rename branch")).
Content(Equals("This branch is tracking a remote. This action will only rename the local branch name, not the name of the remote branch. Continue?")).
Confirm()
t.ExpectPopup().Prompt().
Title(Contains("Enter new branch name")).
InitialText(Equals("master")).
Type("-local").
Confirm()
}).
Press(keys.Universal.Pull)
t.Views().Commits().
Lines(
Contains("two"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/fetch_and_auto_forward_branches_none.go | pkg/integration/tests/sync/fetch_and_auto_forward_branches_none.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var FetchAndAutoForwardBranchesNone = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Fetch from remote and auto-forward branches with config set to 'none'",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
config.GetUserConfig().Git.AutoForwardBranches = "none"
config.GetUserConfig().Git.LocalBranchSortOrder = "alphabetical"
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommits(3)
shell.NewBranch("feature")
shell.NewBranch("diverged")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.SetBranchUpstream("feature", "origin/feature")
shell.SetBranchUpstream("diverged", "origin/diverged")
shell.Checkout("master")
shell.HardReset("HEAD^")
shell.Checkout("feature")
shell.HardReset("HEAD~2")
shell.Checkout("diverged")
shell.HardReset("HEAD~2")
shell.EmptyCommit("local")
shell.NewBranch("checked-out")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ↓2").DoesNotContain("↑"),
Contains("master ↓1").DoesNotContain("↑"),
)
t.Views().Files().
IsFocused().
Press(keys.Files.Fetch)
// AutoForwardBranches is "none": nothing should happen
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ↓2").DoesNotContain("↑"),
Contains("master ↓1").DoesNotContain("↑"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push_tag.go | pkg/integration/tests/sync/push_tag.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PushTag = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push a specific tag",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.CloneIntoRemote("origin")
shell.CreateAnnotatedTag("mytag", "message", "HEAD")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Tags().
Focus().
Lines(
Contains("mytag"),
).
Press(keys.Branches.PushTag)
t.ExpectPopup().Prompt().
Title(Equals("Remote to push tag 'mytag' to:")).
InitialText(Equals("origin")).
SuggestionLines(
Contains("origin"),
).
Confirm()
t.Views().Remotes().
Focus().
Lines(
Contains("origin"),
).
PressEnter()
t.Views().RemoteBranches().
IsFocused().
Lines(
Contains("master"),
).
PressEnter()
t.Views().SubCommits().
IsFocused().
Lines(
Contains("two").Contains("mytag"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/shared.go | pkg/integration/tests/sync/shared.go | package sync
import (
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
func createTwoBranchesReadyToForcePush(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.NewBranch("other_branch")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.SetBranchUpstream("other_branch", "origin/other_branch")
// remove the 'two' commit so that we have something to pull from the remote
shell.HardReset("HEAD^")
shell.Checkout("master")
// doing the same for master
shell.HardReset("HEAD^")
}
func assertSuccessfullyPushed(t *TestDriver) {
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Remotes().
Focus().
Lines(
Contains("origin"),
).
PressEnter()
t.Views().RemoteBranches().
IsFocused().
Lines(
Contains("master"),
).
PressEnter()
t.Views().SubCommits().
IsFocused().
Lines(
Contains("two"),
Contains("one"),
)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push_and_set_upstream.go | pkg/integration/tests/sync/push_and_set_upstream.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PushAndSetUpstream = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push a commit and set the upstream via a prompt",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.CloneIntoRemote("origin")
shell.EmptyCommit("two")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
// assert no mention of upstream/downstream changes
t.Views().Status().Content(Equals("repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
t.ExpectPopup().Prompt().
Title(Equals("Enter upstream as '<remote> <branchname>'")).
SuggestionLines(Equals("origin master")).
ConfirmFirstSuggestion()
assertSuccessfullyPushed(t)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/force_push_multiple_matching.go | pkg/integration/tests/sync/force_push_multiple_matching.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var ForcePushMultipleMatching = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Force push to multiple branches because the user has push.default matching",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.SetConfig("push.default", "matching")
createTwoBranchesReadyToForcePush(shell)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("↓1 repo → master"))
t.Views().Branches().
Lines(
Contains("master ↓1"),
Contains("other_branch ↓1"),
)
t.Views().Files().IsFocused().Press(keys.Universal.Push)
t.ExpectPopup().Confirmation().
Title(Equals("Force push")).
Content(Equals("Your branch has diverged from the remote branch. Press <esc> to cancel, or <enter> to force push.")).
Confirm()
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Branches().
Lines(
Contains("master ✓"),
Contains("other_branch ✓"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_merge.go | pkg/integration/tests/sync/pull_merge.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullMerge = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull with a merge strategy",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file", "content1")
shell.Commit("one")
shell.UpdateFileAndAdd("file", "content2")
shell.Commit("two")
shell.EmptyCommit("three")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.HardReset("HEAD^^")
shell.EmptyCommit("four")
shell.SetConfig("pull.rebase", "false")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("four"),
Contains("one"),
)
t.Views().Status().Content(Equals("↓2↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Pull)
t.Views().Status().Content(Equals("↑2 repo → master"))
t.Views().Commits().
Lines(
Contains("Merge branch 'master' of ../origin"),
Contains("three"),
Contains("two"),
Contains("four"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/force_push.go | pkg/integration/tests/sync/force_push.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var ForcePush = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push to a remote with new commits, requiring a force push",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
// remove the 'two' commit so that we have something to pull from the remote
shell.HardReset("HEAD^")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("↓1 repo → master"))
t.Views().Files().IsFocused().Press(keys.Universal.Push)
t.ExpectPopup().Confirmation().
Title(Equals("Force push")).
Content(Equals("Your branch has diverged from the remote branch. Press <esc> to cancel, or <enter> to force push.")).
Confirm()
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Remotes().Focus().
Lines(Contains("origin")).
PressEnter()
t.Views().RemoteBranches().IsFocused().
Lines(Contains("master")).
PressEnter()
t.Views().SubCommits().IsFocused().
Lines(Contains("one"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push_no_follow_tags.go | pkg/integration/tests/sync/push_no_follow_tags.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PushNoFollowTags = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push with --follow-tags NOT configured in git config",
ExtraCmdArgs: []string{},
Skip: true, // turns out this actually DOES push the tag. I have no idea why
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.CreateAnnotatedTag("mytag", "message", "HEAD")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Remotes().
Focus().
Lines(
Contains("origin"),
).
PressEnter()
t.Views().RemoteBranches().
IsFocused().
Lines(
Contains("master"),
).
PressEnter()
t.Views().SubCommits().
IsFocused().
Lines(
// tag was not pushed to upstream
Contains("two").DoesNotContain("mytag"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull.go | pkg/integration/tests/sync/pull.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Pull = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull a commit from the remote",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
// remove the 'two' commit so that we have something to pull from the remote
shell.HardReset("HEAD^")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("↓1 repo → master"))
t.Views().Files().IsFocused().Press(keys.Universal.Pull)
t.Views().Commits().
Lines(
Contains("two"),
Contains("one"),
)
t.Views().Status().Content(Equals("✓ repo → master"))
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push_follow_tags.go | pkg/integration/tests/sync/push_follow_tags.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PushFollowTags = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push with --follow-tags configured in git config",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.EmptyCommit("two")
shell.CreateAnnotatedTag("mytag", "message", "HEAD")
shell.SetConfig("push.followTags", "true")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Status().Content(Equals("↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Remotes().
Focus().
Lines(
Contains("origin"),
).
PressEnter()
t.Views().RemoteBranches().
IsFocused().
Lines(
Contains("master"),
).
PressEnter()
t.Views().SubCommits().
IsFocused().
Lines(
Contains("two").Contains("mytag"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/fetch_and_auto_forward_branches_all_branches_checked_out_in_other_worktree.go | pkg/integration/tests/sync/fetch_and_auto_forward_branches_all_branches_checked_out_in_other_worktree.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var FetchAndAutoForwardBranchesAllBranchesCheckedOutInOtherWorktree = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Fetch from remote and auto-forward branches with config set to 'allBranches'; check that this skips branches checked out by another worktree",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
config.GetUserConfig().Git.AutoForwardBranches = "allBranches"
config.GetUserConfig().Git.LocalBranchSortOrder = "alphabetical"
},
SetupRepo: func(shell *Shell) {
shell.CreateNCommits(3)
shell.NewBranch("feature")
shell.NewBranch("diverged")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.SetBranchUpstream("feature", "origin/feature")
shell.SetBranchUpstream("diverged", "origin/diverged")
shell.Checkout("master")
shell.HardReset("HEAD^")
shell.Checkout("feature")
shell.HardReset("HEAD~2")
shell.Checkout("diverged")
shell.HardReset("HEAD~2")
shell.EmptyCommit("local")
shell.NewBranch("checked-out")
shell.AddWorktreeCheckout("master", "../linked-worktree")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ↓2").DoesNotContain("↑"),
Contains("master (worktree) ↓1").DoesNotContain("↑"),
)
t.Views().Files().
IsFocused().
Press(keys.Files.Fetch)
// AutoForwardBranches is "allBranches": both master and feature get forwarded
t.Views().Branches().
Lines(
Contains("checked-out").IsSelected(),
Contains("diverged ↓2↑1"),
Contains("feature ✓"),
Contains("master (worktree) ↓1"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/pull_rebase_interactive_conflict.go | pkg/integration/tests/sync/pull_rebase_interactive_conflict.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var PullRebaseInteractiveConflict = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Pull with an interactive rebase strategy, where a conflict occurs",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.CreateFileAndAdd("file", "content1")
shell.Commit("one")
shell.UpdateFileAndAdd("file", "content2")
shell.Commit("two")
shell.CreateFileAndAdd("file3", "content3")
shell.Commit("three")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.HardReset("HEAD^^")
shell.UpdateFileAndAdd("file", "content4")
shell.Commit("four")
shell.CreateFileAndAdd("file5", "content5")
shell.Commit("five")
shell.SetConfig("pull.rebase", "interactive")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("five"),
Contains("four"),
Contains("one"),
)
t.Views().Status().Content(Equals("↓2↑2 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Pull)
t.Common().AcknowledgeConflicts()
t.Views().Commits().
Lines(
Contains("--- Pending rebase todos ---"),
Contains("pick").Contains("five"),
Contains("pick").Contains("CONFLICT").Contains("four"),
Contains("--- Commits ---"),
Contains("three"),
Contains("two"),
Contains("one"),
)
t.Views().Files().
IsFocused().
Lines(
Contains("UU").Contains("file"),
).
PressEnter()
t.Views().MergeConflicts().
IsFocused().
TopLines(
Contains("<<<<<<< HEAD"),
Contains("content2"),
Contains("======="),
Contains("content4"),
Contains(">>>>>>>"),
).
SelectNextItem().
PressPrimaryAction() // choose 'content4'
t.Common().ContinueOnConflictsResolved("rebase")
t.Views().Status().Content(Equals("↑2 repo → master"))
t.Views().Commits().
Focus().
Lines(
Contains("five").IsSelected(),
Contains("four"),
Contains("three"),
Contains("two"),
Contains("one"),
).
SelectNextItem()
t.Views().Main().
Content(
Contains("-content2").
Contains("+content4"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/force_push_remote_branch_not_stored_locally.go | pkg/integration/tests/sync/force_push_remote_branch_not_stored_locally.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var ForcePushRemoteBranchNotStoredLocally = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push a branch whose remote branch is not stored locally, requiring a force push",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.EmptyCommit("two")
shell.Clone("some-remote")
// remove the 'two' commit so that we have something to pull from the remote
shell.HardReset("HEAD^")
shell.SetConfig("branch.master.remote", "../some-remote")
shell.SetConfig("branch.master.pushRemote", "../some-remote")
shell.SetConfig("branch.master.merge", "refs/heads/master")
shell.CreateFileAndAdd("file1", "file1 content")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Contains("? repo → master"))
// We're behind our upstream now, so we expect to be asked to force-push
t.Views().Files().IsFocused().Press(keys.Universal.Push)
t.ExpectPopup().Confirmation().
Title(Equals("Force push")).
Content(Equals("Your branch has diverged from the remote branch. Press <esc> to cancel, or <enter> to force push.")).
Confirm()
// Make a new local commit
t.Views().Files().IsFocused().Press(keys.Files.CommitChanges)
t.ExpectPopup().CommitMessagePanel().Type("new").Confirm()
t.Views().Commits().
Lines(
Contains("new"),
Contains("one"),
)
// Pushing this works without needing to force push
t.Views().Files().IsFocused().Press(keys.Universal.Push)
// Now add the clone as a remote just so that we can check if what we
// pushed arrived there correctly
t.Views().Remotes().Focus().
Press(keys.Universal.New)
t.ExpectPopup().Prompt().
Title(Equals("New remote name:")).Type("some-remote").Confirm()
t.ExpectPopup().Prompt().
Title(Equals("New remote url:")).Type("../some-remote").Confirm()
t.Views().Remotes().Lines(
Contains("some-remote").IsSelected(),
).
PressEnter()
t.Views().RemoteBranches().IsFocused().Lines(
Contains("master").IsSelected(),
).
PressEnter()
t.Views().SubCommits().IsFocused().Lines(
Contains("new"),
Contains("one"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/force_push_multiple_upstream.go | pkg/integration/tests/sync/force_push_multiple_upstream.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var ForcePushMultipleUpstream = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Force push to only the upstream branch of the current branch because the user has push.default upstream",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {},
SetupRepo: func(shell *Shell) {
shell.SetConfig("push.default", "upstream")
createTwoBranchesReadyToForcePush(shell)
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("↓1 repo → master"))
t.Views().Branches().
Lines(
Contains("master ↓1"),
Contains("other_branch ↓1"),
)
t.Views().Files().IsFocused().Press(keys.Universal.Push)
t.ExpectPopup().Confirmation().
Title(Equals("Force push")).
Content(Equals("Your branch has diverged from the remote branch. Press <esc> to cancel, or <enter> to force push.")).
Confirm()
t.Views().Commits().
Lines(
Contains("one"),
)
t.Views().Status().Content(Equals("✓ repo → master"))
t.Views().Branches().
Lines(
Contains("master ✓"),
Contains("other_branch ↓1"),
)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/tests/sync/push.go | pkg/integration/tests/sync/push.go | package sync
import (
"github.com/jesseduffield/lazygit/pkg/config"
. "github.com/jesseduffield/lazygit/pkg/integration/components"
)
var Push = NewIntegrationTest(NewIntegrationTestArgs{
Description: "Push a commit to a pre-configured upstream",
ExtraCmdArgs: []string{},
Skip: false,
SetupConfig: func(config *config.AppConfig) {
},
SetupRepo: func(shell *Shell) {
shell.EmptyCommit("one")
shell.CloneIntoRemote("origin")
shell.SetBranchUpstream("master", "origin/master")
shell.EmptyCommit("two")
},
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Views().Status().Content(Equals("↑1 repo → master"))
t.Views().Files().
IsFocused().
Press(keys.Universal.Push)
assertSuccessfullyPushed(t)
},
})
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/text_matcher.go | pkg/integration/components/text_matcher.go | package components
import (
"fmt"
"regexp"
"strings"
"github.com/samber/lo"
)
type TextMatcher struct {
// If you add or change a field here, be sure to update the copy
// code in checkIsSelected()
*Matcher[string]
}
func (self *TextMatcher) Contains(target string) *TextMatcher {
self.appendRule(matcherRule[string]{
name: fmt.Sprintf("contains '%s'", target),
testFn: func(value string) (bool, string) {
// everything contains the empty string so we unconditionally return true here
if target == "" {
return true, ""
}
return strings.Contains(value, target), fmt.Sprintf("Expected '%s' to be found in '%s'", target, value)
},
})
return self
}
func (self *TextMatcher) DoesNotContain(target string) *TextMatcher {
self.appendRule(matcherRule[string]{
name: fmt.Sprintf("does not contain '%s'", target),
testFn: func(value string) (bool, string) {
return !strings.Contains(value, target), fmt.Sprintf("Expected '%s' to NOT be found in '%s'", target, value)
},
})
return self
}
func (self *TextMatcher) DoesNotContainAnyOf(targets []string) *TextMatcher {
self.appendRule(matcherRule[string]{
name: fmt.Sprintf("does not contain any of '%s'", targets),
testFn: func(value string) (bool, string) {
return lo.NoneBy(targets, func(target string) bool { return strings.Contains(value, target) }),
fmt.Sprintf("Expected none of '%s' to be found in '%s'", targets, value)
},
})
return self
}
func (self *TextMatcher) MatchesRegexp(target string) *TextMatcher {
self.appendRule(matcherRule[string]{
name: fmt.Sprintf("matches regular expression '%s'", target),
testFn: func(value string) (bool, string) {
matched, err := regexp.MatchString(target, value)
if err != nil {
return false, fmt.Sprintf("Unexpected error parsing regular expression '%s': %s", target, err.Error())
}
return matched, fmt.Sprintf("Expected '%s' to match regular expression /%s/", value, target)
},
})
return self
}
func (self *TextMatcher) Equals(target string) *TextMatcher {
self.appendRule(matcherRule[string]{
name: fmt.Sprintf("equals '%s'", target),
testFn: func(value string) (bool, string) {
return target == value, fmt.Sprintf("Expected '%s' to equal '%s'", value, target)
},
})
return self
}
const IS_SELECTED_RULE_NAME = "is selected"
// special rule that is only to be used in the TopLines and Lines methods, as a way of
// asserting that a given line is selected.
func (self *TextMatcher) IsSelected() *TextMatcher {
self.appendRule(matcherRule[string]{
name: IS_SELECTED_RULE_NAME,
testFn: func(value string) (bool, string) {
panic("Special IsSelected matcher is not supposed to have its testFn method called. This rule should only be used within the .Lines() and .TopLines() method on a ViewAsserter.")
},
})
return self
}
// if the matcher has an `IsSelected` rule, it returns true, along with the matcher after that rule has been removed
func (self *TextMatcher) checkIsSelected() (bool, *TextMatcher) {
// copying into a new matcher in case we want to reuse the original later
newMatcher := &TextMatcher{Matcher: &Matcher[string]{}}
*newMatcher.Matcher = *self.Matcher
check := lo.ContainsBy(newMatcher.rules, func(rule matcherRule[string]) bool { return rule.name == IS_SELECTED_RULE_NAME })
newMatcher.rules = lo.Filter(newMatcher.rules, func(rule matcherRule[string], _ int) bool { return rule.name != IS_SELECTED_RULE_NAME })
return check, newMatcher
}
// this matcher has no rules meaning it always passes the test. Use this
// when you don't care what value you're dealing with.
func AnyString() *TextMatcher {
return &TextMatcher{Matcher: &Matcher[string]{}}
}
func Contains(target string) *TextMatcher {
return AnyString().Contains(target)
}
func DoesNotContain(target string) *TextMatcher {
return AnyString().DoesNotContain(target)
}
func DoesNotContainAnyOf(targets ...string) *TextMatcher {
return AnyString().DoesNotContainAnyOf(targets)
}
func MatchesRegexp(target string) *TextMatcher {
return AnyString().MatchesRegexp(target)
}
func Equals(target string) *TextMatcher {
return AnyString().Equals(target)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/menu_driver.go | pkg/integration/components/menu_driver.go | package components
type MenuDriver struct {
t *TestDriver
hasCheckedTitle bool
}
func (self *MenuDriver) getViewDriver() *ViewDriver {
return self.t.Views().Menu()
}
// asserts that the popup has the expected title
func (self *MenuDriver) Title(expected *TextMatcher) *MenuDriver {
self.getViewDriver().Title(expected)
self.hasCheckedTitle = true
return self
}
func (self *MenuDriver) Confirm() *MenuDriver {
self.checkNecessaryChecksCompleted()
self.getViewDriver().Press(self.t.keys.Universal.ConfirmMenu)
return self
}
func (self *MenuDriver) Cancel() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEscape()
}
func (self *MenuDriver) Select(option *TextMatcher) *MenuDriver {
self.getViewDriver().NavigateToLine(option)
return self
}
func (self *MenuDriver) Lines(matchers ...*TextMatcher) *MenuDriver {
self.getViewDriver().Lines(matchers...)
return self
}
func (self *MenuDriver) TopLines(matchers ...*TextMatcher) *MenuDriver {
self.getViewDriver().TopLines(matchers...)
return self
}
func (self *MenuDriver) ContainsLines(matchers ...*TextMatcher) *MenuDriver {
self.getViewDriver().ContainsLines(matchers...)
return self
}
func (self *MenuDriver) Filter(text string) *MenuDriver {
self.getViewDriver().FilterOrSearch(text)
return self
}
func (self *MenuDriver) LineCount(matcher *IntMatcher) *MenuDriver {
self.getViewDriver().LineCount(matcher)
return self
}
func (self *MenuDriver) Wait(milliseconds int) *MenuDriver {
self.getViewDriver().Wait(milliseconds)
return self
}
func (self *MenuDriver) Tooltip(option *TextMatcher) *MenuDriver {
self.t.Views().Tooltip().Content(option)
return self
}
func (self *MenuDriver) Tap(f func()) *MenuDriver {
self.getViewDriver().Tap(f)
return self
}
func (self *MenuDriver) checkNecessaryChecksCompleted() {
if !self.hasCheckedTitle {
self.t.Fail("You must check the title of a menu popup by calling Title() before calling Confirm()/Cancel().")
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/git.go | pkg/integration/components/git.go | package components
import (
"fmt"
"log"
"strings"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
)
type Git struct {
*assertionHelper
shell *Shell
}
func (self *Git) CurrentBranchName(expectedName string) *Git {
return self.assert([]string{"git", "rev-parse", "--abbrev-ref", "HEAD"}, expectedName)
}
func (self *Git) TagNamesAt(ref string, expectedNames []string) *Git {
return self.assert([]string{"git", "tag", "--sort=v:refname", "--points-at", ref}, strings.Join(expectedNames, "\n"))
}
func (self *Git) RemoteTagDeleted(ref string, tagName string) *Git {
return self.expect([]string{"git", "ls-remote", ref, fmt.Sprintf("refs/tags/%s", tagName)}, func(s string) (bool, string) {
return len(s) == 0, fmt.Sprintf("Expected tag %s to have been removed from %s", tagName, ref)
})
}
func (self *Git) assert(cmdArgs []string, expected string) *Git {
self.expect(cmdArgs, func(output string) (bool, string) {
return output == expected, fmt.Sprintf("Expected current branch name to be '%s', but got '%s'", expected, output)
})
return self
}
func (self *Git) expect(cmdArgs []string, condition func(string) (bool, string)) *Git {
self.assertWithRetries(func() (bool, string) {
output, err := self.shell.runCommandWithOutput(cmdArgs)
if err != nil {
return false, fmt.Sprintf("Unexpected error running command: `%v`. Error: %s", cmdArgs, err.Error())
}
actual := strings.TrimSpace(output)
return condition(actual)
})
return self
}
func (self *Git) Version() *git_commands.GitVersion {
version, err := getGitVersion()
if err != nil {
log.Fatalf("Could not get git version: %v", err)
}
return version
}
func (self *Git) GetCommitHash(ref string) string {
output, err := self.shell.runCommandWithOutput([]string{"git", "rev-parse", ref})
if err != nil {
log.Fatalf("Could not get commit hash: %v", err)
}
return strings.TrimSpace(output)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/commit_description_panel_driver.go | pkg/integration/components/commit_description_panel_driver.go | package components
type CommitDescriptionPanelDriver struct {
t *TestDriver
}
func (self *CommitDescriptionPanelDriver) getViewDriver() *ViewDriver {
return self.t.Views().CommitDescription()
}
// asserts on the current context of the description
func (self *CommitDescriptionPanelDriver) Content(expected *TextMatcher) *CommitDescriptionPanelDriver {
self.getViewDriver().Content(expected)
return self
}
func (self *CommitDescriptionPanelDriver) Type(value string) *CommitDescriptionPanelDriver {
self.t.typeContent(value)
return self
}
func (self *CommitDescriptionPanelDriver) SwitchToSummary() *CommitMessagePanelDriver {
self.getViewDriver().PressTab()
return &CommitMessagePanelDriver{t: self.t}
}
func (self *CommitDescriptionPanelDriver) AddNewline() *CommitDescriptionPanelDriver {
self.t.pressFast("<enter>")
return self
}
func (self *CommitDescriptionPanelDriver) GoToBeginning() *CommitDescriptionPanelDriver {
numLines := len(self.getViewDriver().getView().BufferLines())
for range numLines {
self.t.pressFast("<up>")
}
self.t.pressFast("<c-a>")
return self
}
func (self *CommitDescriptionPanelDriver) AddCoAuthor(author string) *CommitDescriptionPanelDriver {
self.t.press(self.t.keys.CommitMessage.CommitMenu)
self.t.ExpectPopup().Menu().Title(Equals("Commit Menu")).
Select(Contains("Add co-author")).
Confirm()
self.t.ExpectPopup().Prompt().Title(Contains("Add co-author")).
Type(author).
Confirm()
return self
}
func (self *CommitDescriptionPanelDriver) Clear() *CommitDescriptionPanelDriver {
self.getViewDriver().Clear()
return self
}
func (self *CommitDescriptionPanelDriver) Title(expected *TextMatcher) *CommitDescriptionPanelDriver {
self.getViewDriver().Title(expected)
return self
}
func (self *CommitDescriptionPanelDriver) Cancel() {
self.getViewDriver().PressEscape()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/prompt_driver.go | pkg/integration/components/prompt_driver.go | package components
type PromptDriver struct {
t *TestDriver
hasCheckedTitle bool
}
func (self *PromptDriver) getViewDriver() *ViewDriver {
return self.t.Views().Prompt()
}
// asserts that the popup has the expected title
func (self *PromptDriver) Title(expected *TextMatcher) *PromptDriver {
self.getViewDriver().Title(expected)
self.hasCheckedTitle = true
return self
}
// asserts on the text initially present in the prompt
func (self *PromptDriver) InitialText(expected *TextMatcher) *PromptDriver {
self.getViewDriver().Content(expected)
return self
}
func (self *PromptDriver) Type(value string) *PromptDriver {
self.t.typeContent(value)
return self
}
func (self *PromptDriver) Clear() *PromptDriver {
self.t.press(ClearKey)
return self
}
func (self *PromptDriver) Confirm() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEnter()
}
func (self *PromptDriver) Cancel() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEscape()
}
func (self *PromptDriver) checkNecessaryChecksCompleted() {
if !self.hasCheckedTitle {
self.t.Fail("You must check the title of a prompt popup by calling Title() before calling Confirm()/Cancel().")
}
}
func (self *PromptDriver) SuggestionLines(matchers ...*TextMatcher) *PromptDriver {
self.t.Views().Suggestions().Lines(matchers...)
return self
}
func (self *PromptDriver) SuggestionTopLines(matchers ...*TextMatcher) *PromptDriver {
self.t.Views().Suggestions().TopLines(matchers...)
return self
}
func (self *PromptDriver) ConfirmFirstSuggestion() {
self.t.press(self.t.keys.Universal.TogglePanel)
self.t.Views().Suggestions().
IsFocused().
SelectedLineIdx(0).
Press(self.t.keys.Universal.ConfirmSuggestion)
}
func (self *PromptDriver) ConfirmSuggestion(matcher *TextMatcher) {
self.t.press(self.t.keys.Universal.TogglePanel)
self.t.Views().Suggestions().
IsFocused().
NavigateToLine(matcher).
Press(self.t.keys.Universal.ConfirmSuggestion)
}
func (self *PromptDriver) DeleteSuggestion(matcher *TextMatcher) *PromptDriver {
self.t.press(self.t.keys.Universal.TogglePanel)
self.t.Views().Suggestions().
IsFocused().
NavigateToLine(matcher)
self.t.press(self.t.keys.Universal.Remove)
return self
}
func (self *PromptDriver) EditSuggestion(matcher *TextMatcher) *PromptDriver {
self.t.press(self.t.keys.Universal.TogglePanel)
self.t.Views().Suggestions().
IsFocused().
NavigateToLine(matcher)
self.t.press(self.t.keys.Universal.Edit)
return self
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/test_driver.go | pkg/integration/components/test_driver.go | package components
import (
"fmt"
"time"
"github.com/atotto/clipboard"
"github.com/jesseduffield/lazygit/pkg/config"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
)
type TestDriver struct {
gui integrationTypes.GuiDriver
keys config.KeybindingConfig
inputDelay int
*assertionHelper
shell *Shell
}
func NewTestDriver(gui integrationTypes.GuiDriver, shell *Shell, keys config.KeybindingConfig, inputDelay int) *TestDriver {
return &TestDriver{
gui: gui,
keys: keys,
inputDelay: inputDelay,
assertionHelper: &assertionHelper{gui: gui},
shell: shell,
}
}
// key is something like 'w' or '<space>'. It's best not to pass a direct value,
// but instead to go through the default user config to get a more meaningful key name
func (self *TestDriver) press(keyStr string) {
self.SetCaption(fmt.Sprintf("Pressing %s", keyStr))
self.gui.PressKey(keyStr)
self.Wait(self.inputDelay)
}
// for use when typing or navigating, because in demos we want that to happen
// faster
func (self *TestDriver) pressFast(keyStr string) {
self.SetCaption("")
self.gui.PressKey(keyStr)
self.Wait(self.inputDelay / 5)
}
func (self *TestDriver) click(x, y int) {
self.SetCaption(fmt.Sprintf("Clicking %d, %d", x, y))
self.gui.Click(x, y)
self.Wait(self.inputDelay)
}
// Should only be used in specific cases where you're doing something weird!
// E.g. invoking a global keybinding from within a popup.
// You probably shouldn't use this function, and should instead go through a view like t.Views().Commit().Focus().Press(...)
func (self *TestDriver) GlobalPress(keyStr string) {
self.press(keyStr)
}
func (self *TestDriver) typeContent(content string) {
for _, char := range content {
self.pressFast(string(char))
}
}
func (self *TestDriver) Common() *Common {
return &Common{t: self}
}
// for when you want to allow lazygit to process something before continuing
func (self *TestDriver) Wait(milliseconds int) {
time.Sleep(time.Duration(milliseconds) * time.Millisecond)
}
func (self *TestDriver) SetCaption(caption string) {
self.gui.SetCaption(caption)
}
func (self *TestDriver) SetCaptionPrefix(prefix string) {
self.gui.SetCaptionPrefix(prefix)
}
func (self *TestDriver) LogUI(message string) {
self.gui.LogUI(message)
}
func (self *TestDriver) Log(message string) {
self.gui.LogUI(message)
}
// allows the user to run shell commands during the test to emulate background activity
func (self *TestDriver) Shell() *Shell {
return self.shell
}
// for making assertions on lazygit views
func (self *TestDriver) Views() *Views {
return &Views{t: self}
}
// for interacting with popups
func (self *TestDriver) ExpectPopup() *Popup {
return &Popup{t: self}
}
func (self *TestDriver) ExpectToast(matcher *TextMatcher) *TestDriver {
t := self.gui.NextToast()
if t == nil {
self.gui.Fail("Expected toast, but didn't get one")
} else {
self.matchString(matcher, "Unexpected toast message",
func() string {
return *t
},
)
}
return self
}
func (self *TestDriver) ExpectClipboard(matcher *TextMatcher) {
self.assertWithRetries(func() (bool, string) {
text, err := clipboard.ReadAll()
if err != nil {
return false, "Error occurred when reading from clipboard: " + err.Error()
}
ok, _ := matcher.test(text)
return ok, fmt.Sprintf("Expected clipboard to match %s, but got %s", matcher.name(), text)
})
}
func (self *TestDriver) ExpectSearch() *SearchDriver {
self.inSearch()
return &SearchDriver{t: self}
}
func (self *TestDriver) inSearch() {
self.assertWithRetries(func() (bool, string) {
currentView := self.gui.CurrentContext().GetView()
return currentView.Name() == "search", "Expected search prompt to be focused"
})
}
// for making assertions through git itself
func (self *TestDriver) Git() *Git {
return &Git{assertionHelper: self.assertionHelper, shell: self.shell}
}
// for making assertions on the file system
func (self *TestDriver) FileSystem() *FileSystem {
return &FileSystem{assertionHelper: self.assertionHelper}
}
// for when you just want to fail the test yourself.
// This runs callbacks to ensure we render the error after closing the gui.
func (self *TestDriver) Fail(message string) {
self.assertionHelper.fail(message)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/popup.go | pkg/integration/components/popup.go | package components
type Popup struct {
t *TestDriver
}
func (self *Popup) Confirmation() *ConfirmationDriver {
self.inConfirm()
return &ConfirmationDriver{t: self.t}
}
func (self *Popup) inConfirm() {
self.t.assertWithRetries(func() (bool, string) {
currentView := self.t.gui.CurrentContext().GetView()
return currentView.Name() == "confirmation", "Expected confirmation popup to be focused"
})
}
func (self *Popup) Prompt() *PromptDriver {
self.inPrompt()
return &PromptDriver{t: self.t}
}
func (self *Popup) inPrompt() {
self.t.assertWithRetries(func() (bool, string) {
currentView := self.t.gui.CurrentContext().GetView()
return currentView.Name() == "prompt", "Expected prompt popup to be focused"
})
}
func (self *Popup) Alert() *AlertDriver {
self.inAlert()
return &AlertDriver{t: self.t}
}
func (self *AlertDriver) Tap(f func()) *AlertDriver {
self.getViewDriver().Tap(f)
return self
}
func (self *Popup) inAlert() {
// basically the same thing as a confirmation popup with the current implementation
self.t.assertWithRetries(func() (bool, string) {
currentView := self.t.gui.CurrentContext().GetView()
return currentView.Name() == "confirmation", "Expected alert popup to be focused"
})
}
func (self *Popup) Menu() *MenuDriver {
self.inMenu()
return &MenuDriver{t: self.t}
}
func (self *Popup) inMenu() {
self.t.assertWithRetries(func() (bool, string) {
return self.t.gui.CurrentContext().GetView().Name() == "menu", "Expected popup menu to be focused"
})
}
func (self *Popup) CommitMessagePanel() *CommitMessagePanelDriver {
self.inCommitMessagePanel()
return &CommitMessagePanelDriver{t: self.t}
}
func (self *Popup) CommitDescriptionPanel() *CommitMessagePanelDriver {
self.inCommitDescriptionPanel()
return &CommitMessagePanelDriver{t: self.t}
}
func (self *Popup) inCommitMessagePanel() {
self.t.assertWithRetries(func() (bool, string) {
currentView := self.t.gui.CurrentContext().GetView()
return currentView.Name() == "commitMessage", "Expected commit message panel to be focused"
})
}
func (self *Popup) inCommitDescriptionPanel() {
self.t.assertWithRetries(func() (bool, string) {
currentView := self.t.gui.CurrentContext().GetView()
return currentView.Name() == "commitDescription", "Expected commit description panel to be focused"
})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/alert_driver.go | pkg/integration/components/alert_driver.go | package components
type AlertDriver struct {
t *TestDriver
hasCheckedTitle bool
hasCheckedContent bool
}
func (self *AlertDriver) getViewDriver() *ViewDriver {
return self.t.Views().Confirmation()
}
// asserts that the alert view has the expected title
func (self *AlertDriver) Title(expected *TextMatcher) *AlertDriver {
self.getViewDriver().Title(expected)
self.hasCheckedTitle = true
return self
}
// asserts that the alert view has the expected content
func (self *AlertDriver) Content(expected *TextMatcher) *AlertDriver {
self.getViewDriver().Content(expected)
self.hasCheckedContent = true
return self
}
func (self *AlertDriver) Confirm() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEnter()
}
func (self *AlertDriver) Cancel() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEscape()
}
func (self *AlertDriver) checkNecessaryChecksCompleted() {
if !self.hasCheckedContent || !self.hasCheckedTitle {
self.t.Fail("You must both check the content and title of a confirmation popup by calling Title()/Content() before calling Confirm()/Cancel().")
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/confirmation_driver.go | pkg/integration/components/confirmation_driver.go | package components
type ConfirmationDriver struct {
t *TestDriver
hasCheckedTitle bool
hasCheckedContent bool
}
func (self *ConfirmationDriver) getViewDriver() *ViewDriver {
return self.t.Views().Confirmation()
}
// asserts that the confirmation view has the expected title
func (self *ConfirmationDriver) Title(expected *TextMatcher) *ConfirmationDriver {
self.getViewDriver().Title(expected)
self.hasCheckedTitle = true
return self
}
// asserts that the confirmation view has the expected content
func (self *ConfirmationDriver) Content(expected *TextMatcher) *ConfirmationDriver {
self.getViewDriver().Content(expected)
self.hasCheckedContent = true
return self
}
func (self *ConfirmationDriver) Confirm() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEnter()
}
func (self *ConfirmationDriver) Cancel() {
self.checkNecessaryChecksCompleted()
self.getViewDriver().PressEscape()
}
func (self *ConfirmationDriver) Wait(milliseconds int) *ConfirmationDriver {
self.getViewDriver().Wait(milliseconds)
return self
}
func (self *ConfirmationDriver) checkNecessaryChecksCompleted() {
if !self.hasCheckedContent || !self.hasCheckedTitle {
self.t.Fail("You must both check the content and title of a confirmation popup by calling Title()/Content() before calling Confirm()/Cancel().")
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/shell.go | pkg/integration/components/shell.go | package components
import (
"fmt"
"io"
"math/rand"
"os"
"os/exec"
"path/filepath"
"runtime"
"time"
)
// this is for running shell commands, mostly for the sake of setting up the repo
// but you can also run the commands from within lazygit to emulate things happening
// in the background.
type Shell struct {
// working directory the shell is invoked in
dir string
// passed into each command
env []string
// when running the shell outside the gui we can directly panic on failure,
// but inside the gui we need to close the gui before panicking
fail func(string)
randomFileContentIndex int
}
func NewShell(dir string, env []string, fail func(string)) *Shell {
return &Shell{dir: dir, env: env, fail: fail}
}
func (self *Shell) RunCommand(args []string) *Shell {
return self.RunCommandWithEnv(args, []string{})
}
// Run a command with additional environment variables set
func (self *Shell) RunCommandWithEnv(args []string, env []string) *Shell {
output, err := self.runCommandWithOutputAndEnv(args, env)
if err != nil {
self.fail(fmt.Sprintf("error running command: %v\n%s", args, output))
}
return self
}
func (self *Shell) RunCommandExpectError(args []string) *Shell {
output, err := self.runCommandWithOutput(args)
if err == nil {
self.fail(fmt.Sprintf("Expected error running shell command: %v\n%s", args, output))
}
return self
}
func (self *Shell) runCommandWithOutput(args []string) (string, error) {
return self.runCommandWithOutputAndEnv(args, []string{})
}
func (self *Shell) runCommandWithOutputAndEnv(args []string, env []string) (string, error) {
cmd := exec.Command(args[0], args[1:]...)
cmd.Env = append(self.env, env...)
cmd.Dir = self.dir
output, err := cmd.CombinedOutput()
return string(output), err
}
func (self *Shell) RunShellCommand(cmdStr string) *Shell {
shell := "sh"
shellArg := "-c"
if runtime.GOOS == "windows" {
shell = "cmd"
shellArg = "/C"
}
cmd := exec.Command(shell, shellArg, cmdStr)
cmd.Env = os.Environ()
cmd.Dir = self.dir
output, err := cmd.CombinedOutput()
if err != nil {
self.fail(fmt.Sprintf("error running shell command: %s\n%s", cmdStr, string(output)))
}
return self
}
func (self *Shell) CreateFile(path string, content string) *Shell {
fullPath := filepath.Join(self.dir, path)
// create any required directories
dir := filepath.Dir(fullPath)
if err := os.MkdirAll(dir, 0o755); err != nil {
self.fail(fmt.Sprintf("error creating directory: %s\n%s", dir, err))
}
err := os.WriteFile(fullPath, []byte(content), 0o644)
if err != nil {
self.fail(fmt.Sprintf("error creating file: %s\n%s", fullPath, err))
}
return self
}
func (self *Shell) DeleteFile(path string) *Shell {
fullPath := filepath.Join(self.dir, path)
err := os.RemoveAll(fullPath)
if err != nil {
self.fail(fmt.Sprintf("error deleting file: %s\n%s", fullPath, err))
}
return self
}
func (self *Shell) CreateDir(path string) *Shell {
fullPath := filepath.Join(self.dir, path)
if err := os.MkdirAll(fullPath, 0o755); err != nil {
self.fail(fmt.Sprintf("error creating directory: %s\n%s", fullPath, err))
}
return self
}
func (self *Shell) UpdateFile(path string, content string) *Shell {
fullPath := filepath.Join(self.dir, path)
err := os.WriteFile(fullPath, []byte(content), 0o644)
if err != nil {
self.fail(fmt.Sprintf("error updating file: %s\n%s", fullPath, err))
}
return self
}
func (self *Shell) NewBranch(name string) *Shell {
return self.RunCommand([]string{"git", "checkout", "-b", name})
}
func (self *Shell) NewBranchFrom(name string, from string) *Shell {
return self.RunCommand([]string{"git", "checkout", "-b", name, from})
}
func (self *Shell) RenameCurrentBranch(newName string) *Shell {
return self.RunCommand([]string{"git", "branch", "-m", newName})
}
func (self *Shell) Checkout(name string) *Shell {
return self.RunCommand([]string{"git", "checkout", name})
}
func (self *Shell) Merge(name string) *Shell {
return self.RunCommand([]string{"git", "merge", "--commit", "--no-ff", name})
}
func (self *Shell) ContinueMerge() *Shell {
return self.RunCommand([]string{"git", "-c", "core.editor=true", "merge", "--continue"})
}
func (self *Shell) GitAdd(path string) *Shell {
return self.RunCommand([]string{"git", "add", path})
}
func (self *Shell) GitAddAll() *Shell {
return self.RunCommand([]string{"git", "add", "-A"})
}
func (self *Shell) Commit(message string) *Shell {
return self.RunCommand([]string{"git", "commit", "-m", message})
}
func (self *Shell) CommitInWorktreeOrSubmodule(worktreePath string, message string) *Shell {
return self.RunCommand([]string{"git", "-C", worktreePath, "commit", "-m", message})
}
func (self *Shell) EmptyCommit(message string) *Shell {
return self.RunCommand([]string{"git", "commit", "--allow-empty", "-m", message})
}
func (self *Shell) EmptyCommitWithBody(subject string, body string) *Shell {
return self.RunCommand([]string{"git", "commit", "--allow-empty", "-m", subject, "-m", body})
}
func (self *Shell) EmptyCommitDaysAgo(message string, daysAgo int) *Shell {
return self.RunCommand([]string{"git", "commit", "--allow-empty", "--date", fmt.Sprintf("%d days ago", daysAgo), "-m", message})
}
func (self *Shell) EmptyCommitWithDate(message string, date string) *Shell {
env := []string{
"GIT_AUTHOR_DATE=" + date,
"GIT_COMMITTER_DATE=" + date,
}
return self.RunCommandWithEnv([]string{"git", "commit", "--allow-empty", "-m", message}, env)
}
func (self *Shell) Revert(ref string) *Shell {
return self.RunCommand([]string{"git", "revert", ref})
}
func (self *Shell) AssertRemoteTagNotFound(upstream, name string) *Shell {
return self.RunCommandExpectError([]string{"git", "ls-remote", "--exit-code", upstream, fmt.Sprintf("refs/tags/%s", name)})
}
func (self *Shell) CreateLightweightTag(name string, ref string) *Shell {
return self.RunCommand([]string{"git", "tag", name, ref})
}
func (self *Shell) CreateAnnotatedTag(name string, message string, ref string) *Shell {
return self.RunCommand([]string{"git", "tag", "-a", name, "-m", message, ref})
}
func (self *Shell) PushBranch(upstream, branch string) *Shell {
return self.RunCommand([]string{"git", "push", upstream, branch})
}
func (self *Shell) PushBranchAndSetUpstream(upstream, branch string) *Shell {
return self.RunCommand([]string{"git", "push", "--set-upstream", upstream, branch})
}
// convenience method for creating a file and adding it
func (self *Shell) CreateFileAndAdd(fileName string, fileContents string) *Shell {
return self.
CreateFile(fileName, fileContents).
GitAdd(fileName)
}
// convenience method for updating a file and adding it
func (self *Shell) UpdateFileAndAdd(fileName string, fileContents string) *Shell {
return self.
UpdateFile(fileName, fileContents).
GitAdd(fileName)
}
// convenience method for deleting a file and adding it
func (self *Shell) DeleteFileAndAdd(fileName string) *Shell {
return self.
DeleteFile(fileName).
GitAdd(fileName)
}
func (self *Shell) RenameFileInGit(oldName string, newName string) *Shell {
return self.RunCommand([]string{"git", "mv", oldName, newName})
}
// creates commits 01, 02, 03, ..., n with a new file in each
// The reason for padding with zeroes is so that it's easier to do string
// matches on the commit messages when there are many of them
func (self *Shell) CreateNCommits(n int) *Shell {
return self.CreateNCommitsStartingAt(n, 1)
}
func (self *Shell) CreateNCommitsStartingAt(n, startIndex int) *Shell {
for i := startIndex; i < startIndex+n; i++ {
self.CreateFileAndAdd(
fmt.Sprintf("file%02d.txt", i),
fmt.Sprintf("file%02d content", i),
).
Commit(fmt.Sprintf("commit %02d", i))
}
return self
}
// Only to be used in demos, because the list might change and we don't want
// tests to break when it does.
func (self *Shell) CreateNCommitsWithRandomMessages(n int) *Shell {
for i := range n {
file := RandomFiles[i]
self.CreateFileAndAdd(
file.Name,
file.Content,
).
Commit(RandomCommitMessages[i])
}
return self
}
// This creates a repo history of commits
// It uses a branching strategy where each feature branch is directly branched off
// of the master branch
// Only to be used in demos
func (self *Shell) CreateRepoHistory() *Shell {
authors := []string{"Yang Wen-li", "Siegfried Kircheis", "Paul Oberstein", "Oscar Reuenthal", "Fredrica Greenhill"}
numAuthors := 5
numBranches := 10
numInitialCommits := 20
maxCommitsPerBranch := 5
// Each commit will happen on a separate day
repoStartDaysAgo := 100
totalCommits := 0
// Generate commits
for i := range numInitialCommits {
author := authors[i%numAuthors]
commitMessage := RandomCommitMessages[totalCommits%len(RandomCommitMessages)]
self.SetAuthor(author, "")
self.EmptyCommitDaysAgo(commitMessage, repoStartDaysAgo-totalCommits)
totalCommits++
}
// Generate branches and merges
for i := range numBranches {
// We'll have one author creating all the commits in the branch
author := authors[i%numAuthors]
branchName := RandomBranchNames[i%len(RandomBranchNames)]
// Choose a random commit within the last 20 commits on the master branch
lastMasterCommit := totalCommits - 1
commitOffset := rand.Intn(min(lastMasterCommit, 5)) + 1
// Create the feature branch and checkout the chosen commit
self.NewBranchFrom(branchName, fmt.Sprintf("master~%d", commitOffset))
numCommitsInBranch := rand.Intn(maxCommitsPerBranch) + 1
for range numCommitsInBranch {
commitMessage := RandomCommitMessages[totalCommits%len(RandomCommitMessages)]
self.SetAuthor(author, "")
self.EmptyCommitDaysAgo(commitMessage, repoStartDaysAgo-totalCommits)
totalCommits++
}
self.Checkout("master")
prevCommitterDate := os.Getenv("GIT_COMMITTER_DATE")
prevAuthorDate := os.Getenv("GIT_AUTHOR_DATE")
commitDate := time.Now().Add(time.Duration(totalCommits-repoStartDaysAgo) * time.Hour * 24)
os.Setenv("GIT_COMMITTER_DATE", commitDate.Format(time.RFC3339))
os.Setenv("GIT_AUTHOR_DATE", commitDate.Format(time.RFC3339))
// Merge branch into master
self.RunCommand([]string{"git", "merge", "--no-ff", branchName, "-m", fmt.Sprintf("Merge %s into master", branchName)})
os.Setenv("GIT_COMMITTER_DATE", prevCommitterDate)
os.Setenv("GIT_AUTHOR_DATE", prevAuthorDate)
}
return self
}
// Creates a commit with a random file
// Only to be used in demos
func (self *Shell) RandomChangeCommit(message string) *Shell {
index := self.randomFileContentIndex
self.randomFileContentIndex++
randomFileName := fmt.Sprintf("random-%d.go", index)
self.CreateFileAndAdd(randomFileName, RandomFileContents[index%len(RandomFileContents)])
return self.Commit(message)
}
func (self *Shell) SetConfig(key string, value string) *Shell {
self.RunCommand([]string{"git", "config", "--local", key, value})
return self
}
func (self *Shell) CloneIntoRemote(name string) *Shell {
self.Clone(name)
self.RunCommand([]string{"git", "remote", "add", name, "../" + name})
self.RunCommand([]string{"git", "fetch", name})
return self
}
func (self *Shell) CloneIntoSubmodule(submoduleName string, submodulePath string) *Shell {
self.Clone(submoduleName)
self.RunCommand([]string{"git", "submodule", "add", "--name", submoduleName, "../" + submoduleName, submodulePath})
return self
}
func (self *Shell) Clone(repoName string) *Shell {
self.RunCommand([]string{"git", "clone", "--bare", ".", "../" + repoName})
return self
}
func (self *Shell) CloneNonBare(repoName string) *Shell {
self.RunCommand([]string{"git", "clone", ".", "../" + repoName})
return self
}
func (self *Shell) SetBranchUpstream(branch string, upstream string) *Shell {
self.RunCommand([]string{"git", "branch", "--set-upstream-to=" + upstream, branch})
return self
}
func (self *Shell) RemoveBranch(branch string) *Shell {
self.RunCommand([]string{"git", "branch", "-d", branch})
return self
}
func (self *Shell) RemoveRemoteBranch(remoteName string, branch string) *Shell {
self.RunCommand([]string{"git", "-C", "../" + remoteName, "branch", "-d", branch})
return self
}
func (self *Shell) HardReset(ref string) *Shell {
self.RunCommand([]string{"git", "reset", "--hard", ref})
return self
}
func (self *Shell) Stash(message string) *Shell {
self.RunCommand([]string{"git", "stash", "push", "-m", message})
return self
}
func (self *Shell) StartBisect(good string, bad string) *Shell {
self.RunCommand([]string{"git", "bisect", "start", good, bad})
return self
}
func (self *Shell) Init() *Shell {
self.RunCommand([]string{"git", "-c", "init.defaultBranch=master", "init"})
return self
}
func (self *Shell) AddWorktree(base string, path string, newBranchName string) *Shell {
return self.RunCommand([]string{
"git", "worktree", "add", "-b",
newBranchName, path, base,
})
}
// add worktree and have it checkout the base branch
func (self *Shell) AddWorktreeCheckout(base string, path string) *Shell {
return self.RunCommand([]string{
"git", "worktree", "add", path, base,
})
}
func (self *Shell) AddFileInWorktreeOrSubmodule(worktreePath string, filePath string, content string) *Shell {
self.CreateFile(filepath.Join(worktreePath, filePath), content)
self.RunCommand([]string{
"git", "-C", worktreePath, "add", filePath,
})
return self
}
func (self *Shell) UpdateFileInWorktreeOrSubmodule(worktreePath string, filePath string, content string) *Shell {
self.UpdateFile(filepath.Join(worktreePath, filePath), content)
self.RunCommand([]string{
"git", "-C", worktreePath, "add", filePath,
})
return self
}
func (self *Shell) MakeExecutable(path string) *Shell {
// 0755 sets the executable permission for owner, and read/execute permissions for group and others
err := os.Chmod(filepath.Join(self.dir, path), 0o755)
if err != nil {
panic(err)
}
return self
}
// Help files are located at test/files from the root the lazygit repo.
// E.g. You may want to create a pre-commit hook file there, then call this
// function to copy it into your test repo.
func (self *Shell) CopyHelpFile(source string, destination string) *Shell {
return self.CopyFile(fmt.Sprintf("../../../../../files/%s", source), destination)
}
func (self *Shell) CopyFile(source string, destination string) *Shell {
absSourcePath := filepath.Join(self.dir, source)
absDestPath := filepath.Join(self.dir, destination)
sourceFile, err := os.Open(absSourcePath)
if err != nil {
self.fail(err.Error())
}
defer sourceFile.Close()
destinationFile, err := os.Create(absDestPath)
if err != nil {
self.fail(err.Error())
}
defer destinationFile.Close()
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
self.fail(err.Error())
}
// copy permissions to destination file too
sourceFileInfo, err := os.Stat(absSourcePath)
if err != nil {
self.fail(err.Error())
}
err = os.Chmod(absDestPath, sourceFileInfo.Mode())
if err != nil {
self.fail(err.Error())
}
return self
}
// The final value passed to Chdir() during setup
// will be the directory the test is run from.
func (self *Shell) Chdir(path string) *Shell {
self.dir = filepath.Join(self.dir, path)
return self
}
func (self *Shell) SetAuthor(authorName string, authorEmail string) *Shell {
self.RunCommand([]string{"git", "config", "--local", "user.name", authorName})
self.RunCommand([]string{"git", "config", "--local", "user.email", authorEmail})
return self
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/assertion_helper.go | pkg/integration/components/assertion_helper.go | package components
import (
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
)
type assertionHelper struct {
gui integrationTypes.GuiDriver
}
func (self *assertionHelper) matchString(matcher *TextMatcher, context string, getValue func() string) {
self.assertWithRetries(func() (bool, string) {
value := getValue()
return matcher.context(context).test(value)
})
}
// We no longer assert with retries now that lazygit tells us when it's no longer
// busy. But I'm keeping the function in case we want to re-introduce it later.
func (self *assertionHelper) assertWithRetries(test func() (bool, string)) {
ok, message := test()
if !ok {
self.fail(message)
}
}
func (self *assertionHelper) fail(message string) {
self.gui.Fail(message)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/views.go | pkg/integration/components/views.go | package components
import (
"fmt"
"github.com/jesseduffield/gocui"
)
type Views struct {
t *TestDriver
}
func (self *Views) Main() *ViewDriver {
return &ViewDriver{
context: "main view",
getView: func() *gocui.View { return self.t.gui.MainView() },
t: self.t,
}
}
func (self *Views) Secondary() *ViewDriver {
return &ViewDriver{
context: "secondary view",
getView: func() *gocui.View { return self.t.gui.SecondaryView() },
t: self.t,
}
}
func (self *Views) regularView(viewName string) *ViewDriver {
return &ViewDriver{
context: fmt.Sprintf("%s view", viewName),
getView: func() *gocui.View { return self.t.gui.View(viewName) },
t: self.t,
}
}
func (self *Views) patchExplorerViewByName(viewName string) *ViewDriver {
return self.regularView(viewName)
}
func (self *Views) MergeConflicts() *ViewDriver {
return self.regularView("mergeConflicts")
}
func (self *Views) Commits() *ViewDriver {
return self.regularView("commits")
}
func (self *Views) Files() *ViewDriver {
return self.regularView("files")
}
func (self *Views) Worktrees() *ViewDriver {
return self.regularView("worktrees")
}
func (self *Views) Status() *ViewDriver {
return self.regularView("status")
}
func (self *Views) Submodules() *ViewDriver {
return self.regularView("submodules")
}
func (self *Views) Information() *ViewDriver {
return self.regularView("information")
}
func (self *Views) AppStatus() *ViewDriver {
return self.regularView("appStatus")
}
func (self *Views) Branches() *ViewDriver {
return self.regularView("localBranches")
}
func (self *Views) Remotes() *ViewDriver {
return self.regularView("remotes")
}
func (self *Views) RemoteBranches() *ViewDriver {
return self.regularView("remoteBranches")
}
func (self *Views) Tags() *ViewDriver {
return self.regularView("tags")
}
func (self *Views) ReflogCommits() *ViewDriver {
return self.regularView("reflogCommits")
}
func (self *Views) SubCommits() *ViewDriver {
return self.regularView("subCommits")
}
func (self *Views) CommitFiles() *ViewDriver {
return self.regularView("commitFiles")
}
func (self *Views) Stash() *ViewDriver {
return self.regularView("stash")
}
func (self *Views) Staging() *ViewDriver {
return self.patchExplorerViewByName("staging")
}
func (self *Views) StagingSecondary() *ViewDriver {
return self.patchExplorerViewByName("stagingSecondary")
}
func (self *Views) PatchBuilding() *ViewDriver {
return self.patchExplorerViewByName("patchBuilding")
}
func (self *Views) PatchBuildingSecondary() *ViewDriver {
// this is not a patch explorer view because you can't actually focus it: it
// just renders content
return self.regularView("patchBuildingSecondary")
}
func (self *Views) Menu() *ViewDriver {
return self.regularView("menu")
}
func (self *Views) Confirmation() *ViewDriver {
return self.regularView("confirmation")
}
func (self *Views) Prompt() *ViewDriver {
return self.regularView("prompt")
}
func (self *Views) CommitMessage() *ViewDriver {
return self.regularView("commitMessage")
}
func (self *Views) CommitDescription() *ViewDriver {
return self.regularView("commitDescription")
}
func (self *Views) Suggestions() *ViewDriver {
return self.regularView("suggestions")
}
func (self *Views) Search() *ViewDriver {
return self.regularView("search")
}
func (self *Views) Tooltip() *ViewDriver {
return self.regularView("tooltip")
}
func (self *Views) Options() *ViewDriver {
return self.regularView("options")
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/runner.go | pkg/integration/components/runner.go | package components
import (
"fmt"
"os"
"os/exec"
"path/filepath"
lazycoreUtils "github.com/jesseduffield/lazycore/pkg/utils"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
type RunTestArgs struct {
Tests []*IntegrationTest
Logf func(format string, formatArgs ...any)
RunCmd func(cmd *exec.Cmd) (int, error)
TestWrapper func(test *IntegrationTest, f func() error)
Sandbox bool
WaitForDebugger bool
RaceDetector bool
CodeCoverageDir string
InputDelay int
MaxAttempts int
}
// This function lets you run tests either from within `go test` or from a regular binary.
// The reason for having two separate ways of testing is that `go test` isn't great at
// showing what's actually happening during the test, but it's still good at running
// tests in telling you about their results.
func RunTests(args RunTestArgs) error {
projectRootDir := lazycoreUtils.GetLazyRootDirectory()
err := os.Chdir(projectRootDir)
if err != nil {
return err
}
testDir := filepath.Join(projectRootDir, "test", "_results")
if err := buildLazygit(args); err != nil {
return err
}
gitVersion, err := getGitVersion()
if err != nil {
return err
}
for _, test := range args.Tests {
args.TestWrapper(test, func() error {
paths := NewPaths(
filepath.Join(testDir, test.Name()),
)
for i := range args.MaxAttempts {
err := runTest(test, args, paths, projectRootDir, gitVersion)
if err != nil {
if i == args.MaxAttempts-1 {
return err
}
args.Logf("retrying test %s", test.Name())
} else {
break
}
}
return nil
})
}
return nil
}
func runTest(
test *IntegrationTest,
args RunTestArgs,
paths Paths,
projectRootDir string,
gitVersion *git_commands.GitVersion,
) error {
if test.Skip() {
args.Logf("Skipping test %s", test.Name())
return nil
}
if !test.ShouldRunForGitVersion(gitVersion) {
args.Logf("Skipping test %s for git version %d.%d.%d", test.Name(), gitVersion.Major, gitVersion.Minor, gitVersion.Patch)
return nil
}
workingDir, err := prepareTestDir(test, paths, projectRootDir)
if err != nil {
return err
}
cmd, err := getLazygitCommand(test, args, paths, projectRootDir, workingDir)
if err != nil {
return err
}
pid, err := args.RunCmd(cmd)
// Print race detector log regardless of the command's exit status
if args.RaceDetector {
logPath := fmt.Sprintf("%s.%d", raceDetectorLogsPath(), pid)
if bytes, err := os.ReadFile(logPath); err == nil {
args.Logf("Race detector log:\n" + string(bytes))
}
}
return err
}
func prepareTestDir(
test *IntegrationTest,
paths Paths,
rootDir string,
) (string, error) {
findOrCreateDir(paths.Root())
deleteAndRecreateEmptyDir(paths.Actual())
err := os.Mkdir(paths.ActualRepo(), 0o777)
if err != nil {
return "", err
}
workingDir := createFixture(test, paths, rootDir)
return workingDir, nil
}
func buildLazygit(testArgs RunTestArgs) error {
args := []string{"go", "build"}
if testArgs.WaitForDebugger {
// Disable compiler optimizations (-N) and inlining (-l) because this
// makes debugging work better
args = append(args, "-gcflags=all=-N -l")
}
if testArgs.RaceDetector {
args = append(args, "-race")
}
if testArgs.CodeCoverageDir != "" {
args = append(args, "-cover")
}
args = append(args, "-o", tempLazygitPath(), filepath.FromSlash("pkg/integration/clients/injector/main.go"))
osCommand := oscommands.NewDummyOSCommand()
return osCommand.Cmd.New(args).Run()
}
// Sets up the fixture for test and returns the working directory to invoke
// lazygit in.
func createFixture(test *IntegrationTest, paths Paths, rootDir string) string {
env := NewTestEnvironment(rootDir)
env = append(env, fmt.Sprintf("%s=%s", PWD, paths.ActualRepo()))
shell := NewShell(
paths.ActualRepo(),
env,
func(errorMsg string) { panic(errorMsg) },
)
shell.Init()
test.SetupRepo(shell)
return shell.dir
}
func testPath(rootdir string) string {
return filepath.Join(rootdir, "test")
}
func globalGitConfigPath(rootDir string) string {
return filepath.Join(testPath(rootDir), "global_git_config")
}
func getGitVersion() (*git_commands.GitVersion, error) {
osCommand := oscommands.NewDummyOSCommand()
cmdObj := osCommand.Cmd.New([]string{"git", "--version"})
versionStr, err := cmdObj.RunWithOutput()
if err != nil {
return nil, err
}
return git_commands.ParseGitVersion(versionStr)
}
func getLazygitCommand(
test *IntegrationTest,
args RunTestArgs,
paths Paths,
rootDir string,
workingDir string,
) (*exec.Cmd, error) {
osCommand := oscommands.NewDummyOSCommand()
err := os.RemoveAll(paths.Config())
if err != nil {
return nil, err
}
templateConfigDir := filepath.Join(rootDir, "test", "default_test_config")
err = oscommands.CopyDir(templateConfigDir, paths.Config())
if err != nil {
return nil, err
}
cmdArgs := []string{tempLazygitPath(), "-debug", "--use-config-dir=" + paths.Config()}
resolvedExtraArgs := lo.Map(test.ExtraCmdArgs(), func(arg string, _ int) string {
return utils.ResolvePlaceholderString(arg, map[string]string{
"actualPath": paths.Actual(),
"actualRepoPath": paths.ActualRepo(),
})
})
cmdArgs = append(cmdArgs, resolvedExtraArgs...)
// Use a limited environment for test isolation, including pass through
// of just allowed host environment variables
cmdObj := osCommand.Cmd.NewWithEnviron(cmdArgs, NewTestEnvironment(rootDir))
// Integration tests related to symlink behavior need a PWD that
// preserves symlinks. By default, SetWd will set a symlink-resolved
// value for PWD. Here, we override that with the path (that may)
// contain a symlink to simulate behavior in a user's shell correctly.
cmdObj.SetWd(workingDir)
cmdObj.AddEnvVars(fmt.Sprintf("%s=%s", PWD, workingDir))
cmdObj.AddEnvVars(fmt.Sprintf("%s=%s", LAZYGIT_ROOT_DIR, rootDir))
if args.CodeCoverageDir != "" {
// We set this explicitly here rather than inherit it from the test runner's
// environment because the test runner has its own coverage directory that
// it writes to and so if we pass GOCOVERDIR to that, it will be overwritten.
cmdObj.AddEnvVars("GOCOVERDIR=" + args.CodeCoverageDir)
}
cmdObj.AddEnvVars(fmt.Sprintf("%s=%s", TEST_NAME_ENV_VAR, test.Name()))
if args.Sandbox {
cmdObj.AddEnvVars(fmt.Sprintf("%s=%s", SANDBOX_ENV_VAR, "true"))
}
if args.WaitForDebugger {
cmdObj.AddEnvVars(fmt.Sprintf("%s=true", WAIT_FOR_DEBUGGER_ENV_VAR))
}
// Set a race detector log path only to avoid spamming the terminal with the
// logs. We are not showing this anywhere yet.
cmdObj.AddEnvVars(fmt.Sprintf("GORACE=log_path=%s", raceDetectorLogsPath()))
if test.ExtraEnvVars() != nil {
for key, value := range test.ExtraEnvVars() {
cmdObj.AddEnvVars(fmt.Sprintf("%s=%s", key, value))
}
}
if args.InputDelay > 0 {
cmdObj.AddEnvVars(fmt.Sprintf("INPUT_DELAY=%d", args.InputDelay))
}
cmdObj.AddEnvVars(fmt.Sprintf("%s=%s", GIT_CONFIG_GLOBAL_ENV_VAR, globalGitConfigPath(rootDir)))
return cmdObj.GetCmd(), nil
}
func tempLazygitPath() string {
return filepath.Join("/tmp", "lazygit", "test_lazygit")
}
func raceDetectorLogsPath() string {
return filepath.Join("/tmp", "lazygit", "race_log")
}
func findOrCreateDir(path string) {
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(path, 0o777)
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
}
func deleteAndRecreateEmptyDir(path string) {
// remove contents of integration test directory
dir, err := os.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
err = os.Mkdir(path, 0o777)
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
for _, d := range dir {
os.RemoveAll(filepath.Join(path, d.Name()))
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/paths.go | pkg/integration/components/paths.go | package components
import "path/filepath"
// convenience struct for easily getting directories within our test directory.
// We have one test directory for each test, found in test/_results.
type Paths struct {
// e.g. test/_results/test_name
root string
}
func NewPaths(root string) Paths {
return Paths{root: root}
}
// when a test first runs, it's situated in a repo called 'repo' within this
// directory. In its setup step, the test is allowed to create other repos
// alongside the 'repo' repo in this directory, for example, creating remotes
// or repos to add as submodules.
func (self Paths) Actual() string {
return filepath.Join(self.root, "actual")
}
// this is the 'repo' directory within the 'actual' directory,
// where a lazygit test will start within.
func (self Paths) ActualRepo() string {
return filepath.Join(self.Actual(), "repo")
}
func (self Paths) Config() string {
return filepath.Join(self.root, "used_config")
}
func (self Paths) Root() string {
return self.root
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/env.go | pkg/integration/components/env.go | package components
import (
"fmt"
"os"
)
const (
// These values will be passed to lazygit
LAZYGIT_ROOT_DIR = "LAZYGIT_ROOT_DIR"
SANDBOX_ENV_VAR = "SANDBOX"
TEST_NAME_ENV_VAR = "TEST_NAME"
WAIT_FOR_DEBUGGER_ENV_VAR = "WAIT_FOR_DEBUGGER"
// These values will be passed to both lazygit and shell commands
GIT_CONFIG_GLOBAL_ENV_VAR = "GIT_CONFIG_GLOBAL"
// We pass PWD because if it's defined, Go will use it as the working directory
// rather than make a syscall to the OS, and that means symlinks won't be resolved,
// which is good to test for.
PWD = "PWD"
// We set $HOME and $GIT_CONFIG_NOGLOBAL during integration tests so
// that older versions of git that don't respect $GIT_CONFIG_GLOBAL
// will find the correct global config file for testing
HOME = "HOME"
GIT_CONFIG_NOGLOBAL = "GIT_CONFIG_NOGLOBAL"
// These values will be passed through to lazygit and shell commands, with their
// values inherited from the host environment
PATH = "PATH"
TERM = "TERM"
)
// Tests will inherit these environment variables from the host environment, rather
// than the test runner deciding the values itself.
// All other environment variables present in the host environment will be ignored.
// Having such a minimal list ensures that lazygit behaves the same across different test environments.
var hostEnvironmentAllowlist = [...]string{
PATH,
TERM,
}
// Returns a copy of the environment filtered by
// hostEnvironmentAllowlist
func allowedHostEnvironment() []string {
env := []string{}
for _, envVar := range hostEnvironmentAllowlist {
env = append(env, fmt.Sprintf("%s=%s", envVar, os.Getenv(envVar)))
}
return env
}
func NewTestEnvironment(rootDir string) []string {
env := allowedHostEnvironment()
// Set $HOME to control the global git config location for git
// versions <= 2.31.8
env = append(env, fmt.Sprintf("%s=%s", HOME, testPath(rootDir)))
// $GIT_CONFIG_GLOBAL controls global git config location for git
// versions >= 2.32.0
env = append(env, fmt.Sprintf("%s=%s", GIT_CONFIG_GLOBAL_ENV_VAR, globalGitConfigPath(rootDir)))
return env
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/test.go | pkg/integration/components/test.go | package components
import (
"os"
"strconv"
"strings"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/config"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
// IntegrationTest describes an integration test that will be run against the lazygit gui.
// our unit tests will use this description to avoid a panic caused by attempting
// to get the test's name via it's file's path.
const unitTestDescription = "test test"
const (
defaultWidth = 150
defaultHeight = 100
)
type IntegrationTest struct {
name string
description string
extraCmdArgs []string
extraEnvVars map[string]string
skip bool
setupRepo func(shell *Shell)
setupConfig func(config *config.AppConfig)
run func(
testDriver *TestDriver,
keys config.KeybindingConfig,
)
gitVersion GitVersionRestriction
width int
height int
isDemo bool
}
var _ integrationTypes.IntegrationTest = &IntegrationTest{}
type NewIntegrationTestArgs struct {
// Briefly describes what happens in the test and what it's testing for
Description string
// prepares a repo for testing
SetupRepo func(shell *Shell)
// takes a config and mutates. The mutated context will end up being passed to the gui
SetupConfig func(config *config.AppConfig)
// runs the test
Run func(t *TestDriver, keys config.KeybindingConfig)
// additional args passed to lazygit
ExtraCmdArgs []string
ExtraEnvVars map[string]string
// for when a test is flakey
Skip bool
// to run a test only on certain git versions
GitVersion GitVersionRestriction
// width and height when running in headless mode, for testing
// the UI in different sizes.
// If these are set, the test must be run in headless mode
Width int
Height int
// If true, this is not a test but a demo to be added to our docs
IsDemo bool
}
type GitVersionRestriction struct {
// Only one of these fields can be non-empty; use functions below to construct
from string
before string
includes []string
}
// Verifies the version is at least the given version (inclusive)
func AtLeast(version string) GitVersionRestriction {
return GitVersionRestriction{from: version}
}
// Verifies the version is before the given version (exclusive)
func Before(version string) GitVersionRestriction {
return GitVersionRestriction{before: version}
}
func Includes(versions ...string) GitVersionRestriction {
return GitVersionRestriction{includes: versions}
}
func (self GitVersionRestriction) shouldRunOnVersion(version *git_commands.GitVersion) bool {
if self.from != "" {
from, err := git_commands.ParseGitVersion(self.from)
if err != nil {
panic("Invalid git version string: " + self.from)
}
return version.IsAtLeastVersion(from)
}
if self.before != "" {
before, err := git_commands.ParseGitVersion(self.before)
if err != nil {
panic("Invalid git version string: " + self.before)
}
return version.IsOlderThanVersion(before)
}
if len(self.includes) != 0 {
return lo.SomeBy(self.includes, func(str string) bool {
v, err := git_commands.ParseGitVersion(str)
if err != nil {
panic("Invalid git version string: " + str)
}
return version.Major == v.Major && version.Minor == v.Minor && version.Patch == v.Patch
})
}
return true
}
func NewIntegrationTest(args NewIntegrationTestArgs) *IntegrationTest {
name := ""
if args.Description != unitTestDescription {
// this panics if we're in a unit test for our integration tests,
// so we're using "test test" as a sentinel value
name = testNameFromCurrentFilePath()
}
return &IntegrationTest{
name: name,
description: args.Description,
extraCmdArgs: args.ExtraCmdArgs,
extraEnvVars: args.ExtraEnvVars,
skip: args.Skip,
setupRepo: args.SetupRepo,
setupConfig: args.SetupConfig,
run: args.Run,
gitVersion: args.GitVersion,
width: args.Width,
height: args.Height,
isDemo: args.IsDemo,
}
}
func (self *IntegrationTest) Name() string {
return self.name
}
func (self *IntegrationTest) Description() string {
return self.description
}
func (self *IntegrationTest) ExtraCmdArgs() []string {
return self.extraCmdArgs
}
func (self *IntegrationTest) ExtraEnvVars() map[string]string {
return self.extraEnvVars
}
func (self *IntegrationTest) Skip() bool {
return self.skip
}
func (self *IntegrationTest) IsDemo() bool {
return self.isDemo
}
func (self *IntegrationTest) ShouldRunForGitVersion(version *git_commands.GitVersion) bool {
return self.gitVersion.shouldRunOnVersion(version)
}
func (self *IntegrationTest) SetupConfig(config *config.AppConfig) {
self.setupConfig(config)
}
func (self *IntegrationTest) SetupRepo(shell *Shell) {
self.setupRepo(shell)
}
func (self *IntegrationTest) Run(gui integrationTypes.GuiDriver) {
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
shell := NewShell(
pwd,
// passing the full environment because it's already been filtered down
// in the parent process.
os.Environ(),
func(errorMsg string) { gui.Fail(errorMsg) },
)
keys := gui.Keys()
testDriver := NewTestDriver(gui, shell, keys, InputDelay())
if InputDelay() > 0 {
// Setting caption to clear the options menu from whatever it starts with
testDriver.SetCaption("")
testDriver.SetCaptionPrefix("")
}
self.run(testDriver, keys)
gui.CheckAllToastsAcknowledged()
if InputDelay() > 0 {
// Clear whatever caption there was so it doesn't linger
testDriver.SetCaption("")
testDriver.SetCaptionPrefix("")
// the dev would want to see the final state if they're running in slow mode
testDriver.Wait(2000)
}
}
func (self *IntegrationTest) HeadlessDimensions() (int, int) {
if self.width == 0 && self.height == 0 {
return defaultWidth, defaultHeight
}
return self.width, self.height
}
func (self *IntegrationTest) RequiresHeadless() bool {
return self.width != 0 && self.height != 0
}
func testNameFromCurrentFilePath() string {
path := utils.FilePath(3)
return TestNameFromFilePath(path)
}
func TestNameFromFilePath(path string) string {
name := strings.Split(path, "integration/tests/")[1]
return name[:len(name)-len(".go")]
}
// this is the delay in milliseconds between keypresses or mouse clicks
// defaults to zero
func InputDelay() int {
delayStr := os.Getenv("INPUT_DELAY")
if delayStr == "" {
return 0
}
delay, err := strconv.Atoi(delayStr)
if err != nil {
panic(err)
}
return delay
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/matcher.go | pkg/integration/components/matcher.go | package components
import (
"strings"
"github.com/samber/lo"
)
// for making assertions on string values
type Matcher[T any] struct {
rules []matcherRule[T]
// this is printed when there's an error so that it's clear what the context of the assertion is
prefix string
}
type matcherRule[T any] struct {
// e.g. "contains 'foo'"
name string
// returns a bool that says whether the test passed and if it returns false, it
// also returns a string of the error message
testFn func(T) (bool, string)
}
func (self *Matcher[T]) name() string {
if len(self.rules) == 0 {
return "anything"
}
return strings.Join(
lo.Map(self.rules, func(rule matcherRule[T], _ int) string { return rule.name }),
", ",
)
}
func (self *Matcher[T]) test(value T) (bool, string) {
for _, rule := range self.rules {
ok, message := rule.testFn(value)
if ok {
continue
}
if self.prefix != "" {
return false, self.prefix + " " + message
}
return false, message
}
return true, ""
}
func (self *Matcher[T]) appendRule(rule matcherRule[T]) *Matcher[T] {
self.rules = append(self.rules, rule)
return self
}
// adds context so that if the matcher test(s) fails, we understand what we were trying to test.
// E.g. prefix: "Unexpected content in view 'files'."
func (self *Matcher[T]) context(prefix string) *Matcher[T] {
self.prefix = prefix
return self
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/file_system.go | pkg/integration/components/file_system.go | package components
import (
"fmt"
"os"
)
type FileSystem struct {
*assertionHelper
}
// This does _not_ check the files panel, it actually checks the filesystem
func (self *FileSystem) PathPresent(path string) *FileSystem {
self.assertWithRetries(func() (bool, string) {
_, err := os.Stat(path)
return err == nil, fmt.Sprintf("Expected path '%s' to exist, but it does not", path)
})
return self
}
// This does _not_ check the files panel, it actually checks the filesystem
func (self *FileSystem) PathNotPresent(path string) *FileSystem {
self.assertWithRetries(func() (bool, string) {
_, err := os.Stat(path)
return os.IsNotExist(err), fmt.Sprintf("Expected path '%s' to not exist, but it does", path)
})
return self
}
// Asserts that the file at the given path has the given content
func (self *FileSystem) FileContent(path string, matcher *TextMatcher) *FileSystem {
self.assertWithRetries(func() (bool, string) {
_, err := os.Stat(path)
if os.IsNotExist(err) {
return false, fmt.Sprintf("Expected path '%s' to exist, but it does not", path)
}
output, err := os.ReadFile(path)
if err != nil {
return false, fmt.Sprintf("Expected error when reading file content at path '%s': %s", path, err.Error())
}
strOutput := string(output)
if ok, errMsg := matcher.context("").test(strOutput); !ok {
return false, fmt.Sprintf("Unexpected content in file %s: %s", path, errMsg)
}
return true, ""
})
return self
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/commit_message_panel_driver.go | pkg/integration/components/commit_message_panel_driver.go | package components
type CommitMessagePanelDriver struct {
t *TestDriver
}
func (self *CommitMessagePanelDriver) getViewDriver() *ViewDriver {
return self.t.Views().CommitMessage()
}
// asserts on the text initially present in the prompt
func (self *CommitMessagePanelDriver) InitialText(expected *TextMatcher) *CommitMessagePanelDriver {
return self.Content(expected)
}
// asserts on the current context in the prompt
func (self *CommitMessagePanelDriver) Content(expected *TextMatcher) *CommitMessagePanelDriver {
self.getViewDriver().Content(expected)
return self
}
// asserts that the confirmation view has the expected title
func (self *CommitMessagePanelDriver) Title(expected *TextMatcher) *CommitMessagePanelDriver {
self.getViewDriver().Title(expected)
return self
}
func (self *CommitMessagePanelDriver) Type(value string) *CommitMessagePanelDriver {
self.t.typeContent(value)
return self
}
func (self *CommitMessagePanelDriver) SwitchToDescription() *CommitDescriptionPanelDriver {
self.getViewDriver().PressTab()
return &CommitDescriptionPanelDriver{t: self.t}
}
func (self *CommitMessagePanelDriver) Clear() *CommitMessagePanelDriver {
self.getViewDriver().Clear()
return self
}
func (self *CommitMessagePanelDriver) Confirm() {
self.getViewDriver().PressEnter()
}
func (self *CommitMessagePanelDriver) Close() {
self.getViewDriver().PressEscape()
}
func (self *CommitMessagePanelDriver) Cancel() {
self.getViewDriver().PressEscape()
}
func (self *CommitMessagePanelDriver) SwitchToEditor() {
self.OpenCommitMenu()
self.t.ExpectPopup().Menu().Title(Equals("Commit Menu")).
Select(Contains("Open in editor")).
Confirm()
}
func (self *CommitMessagePanelDriver) SelectPreviousMessage() *CommitMessagePanelDriver {
self.getViewDriver().SelectPreviousItem()
return self
}
func (self *CommitMessagePanelDriver) SelectNextMessage() *CommitMessagePanelDriver {
self.getViewDriver().SelectNextItem()
return self
}
func (self *CommitMessagePanelDriver) OpenCommitMenu() *CommitMessagePanelDriver {
self.t.press(self.t.keys.CommitMessage.CommitMenu)
return self
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/test_test.go | pkg/integration/components/test_test.go | package components
import (
"testing"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/types"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
"github.com/stretchr/testify/assert"
)
// this file is for testing our test code (meta, I know)
type coordinate struct {
x, y int
}
type fakeGuiDriver struct {
failureMessage string
pressedKeys []string
clickedCoordinates []coordinate
}
var _ integrationTypes.GuiDriver = &fakeGuiDriver{}
func (self *fakeGuiDriver) PressKey(key string) {
self.pressedKeys = append(self.pressedKeys, key)
}
func (self *fakeGuiDriver) Click(x, y int) {
self.clickedCoordinates = append(self.clickedCoordinates, coordinate{x: x, y: y})
}
func (self *fakeGuiDriver) Keys() config.KeybindingConfig {
return config.KeybindingConfig{}
}
func (self *fakeGuiDriver) CurrentContext() types.Context {
return nil
}
func (self *fakeGuiDriver) ContextForView(viewName string) types.Context {
return nil
}
func (self *fakeGuiDriver) Fail(message string) {
self.failureMessage = message
}
func (self *fakeGuiDriver) Log(message string) {
}
func (self *fakeGuiDriver) LogUI(message string) {
}
func (self *fakeGuiDriver) CheckedOutRef() *models.Branch {
return nil
}
func (self *fakeGuiDriver) MainView() *gocui.View {
return nil
}
func (self *fakeGuiDriver) SecondaryView() *gocui.View {
return nil
}
func (self *fakeGuiDriver) View(viewName string) *gocui.View {
return nil
}
func (self *fakeGuiDriver) SetCaption(string) {
}
func (self *fakeGuiDriver) SetCaptionPrefix(string) {
}
func (self *fakeGuiDriver) NextToast() *string {
return nil
}
func (self *fakeGuiDriver) CheckAllToastsAcknowledged() {}
func (self *fakeGuiDriver) Headless() bool { return false }
func TestManualFailure(t *testing.T) {
test := NewIntegrationTest(NewIntegrationTestArgs{
Description: unitTestDescription,
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.Fail("blah")
},
})
driver := &fakeGuiDriver{}
test.Run(driver)
assert.Equal(t, "blah", driver.failureMessage)
}
func TestSuccess(t *testing.T) {
test := NewIntegrationTest(NewIntegrationTestArgs{
Description: unitTestDescription,
Run: func(t *TestDriver, keys config.KeybindingConfig) {
t.press("a")
t.press("b")
t.click(0, 1)
t.click(2, 3)
},
})
driver := &fakeGuiDriver{}
test.Run(driver)
assert.EqualValues(t, []string{"a", "b"}, driver.pressedKeys)
assert.EqualValues(t, []coordinate{{0, 1}, {2, 3}}, driver.clickedCoordinates)
assert.Equal(t, "", driver.failureMessage)
}
func TestGitVersionRestriction(t *testing.T) {
scenarios := []struct {
testName string
gitVersion GitVersionRestriction
expectedShouldRun bool
}{
{
testName: "AtLeast, current is newer",
gitVersion: AtLeast("2.24.9"),
expectedShouldRun: true,
},
{
testName: "AtLeast, current is same",
gitVersion: AtLeast("2.25.0"),
expectedShouldRun: true,
},
{
testName: "AtLeast, current is older",
gitVersion: AtLeast("2.26.0"),
expectedShouldRun: false,
},
{
testName: "Before, current is older",
gitVersion: Before("2.24.9"),
expectedShouldRun: false,
},
{
testName: "Before, current is same",
gitVersion: Before("2.25.0"),
expectedShouldRun: false,
},
{
testName: "Before, current is newer",
gitVersion: Before("2.26.0"),
expectedShouldRun: true,
},
{
testName: "Includes, current is included",
gitVersion: Includes("2.23.0", "2.25.0"),
expectedShouldRun: true,
},
{
testName: "Includes, current is not included",
gitVersion: Includes("2.23.0", "2.27.0"),
expectedShouldRun: false,
},
}
currentGitVersion := git_commands.GitVersion{Major: 2, Minor: 25, Patch: 0}
for _, s := range scenarios {
t.Run(s.testName, func(t *testing.T) {
test := NewIntegrationTest(NewIntegrationTestArgs{
Description: unitTestDescription,
GitVersion: s.gitVersion,
})
shouldRun := test.ShouldRunForGitVersion(¤tGitVersion)
assert.Equal(t, shouldRun, s.expectedShouldRun)
})
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/view_driver.go | pkg/integration/components/view_driver.go | package components
import (
"fmt"
"strings"
"github.com/jesseduffield/gocui"
"github.com/samber/lo"
)
type ViewDriver struct {
// context is prepended to any error messages e.g. 'context: "current view"'
context string
getView func() *gocui.View
t *TestDriver
}
func (self *ViewDriver) getSelectedLines() []string {
view := self.t.gui.View(self.getView().Name())
return view.SelectedLines()
}
func (self *ViewDriver) getSelectedRange() (int, int) {
view := self.t.gui.View(self.getView().Name())
return view.SelectedLineRange()
}
func (self *ViewDriver) getSelectedLineIdx() int {
view := self.t.gui.View(self.getView().Name())
return view.SelectedLineIdx()
}
// asserts that the view has the expected title
func (self *ViewDriver) Title(expected *TextMatcher) *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
actual := self.getView().Title
return expected.context(fmt.Sprintf("%s title", self.context)).test(actual)
})
return self
}
func (self *ViewDriver) Clear() *ViewDriver {
// clearing multiple times in case there's multiple lines
// (the clear button only clears a single line at a time)
maxAttempts := 100
for i := range maxAttempts + 1 {
if self.getView().Buffer() == "" {
break
}
self.t.press(ClearKey)
if i == maxAttempts {
panic("failed to clear view buffer")
}
}
return self
}
// asserts that the view has lines matching the given matchers. One matcher must be passed for each line.
// If you only care about the top n lines, use the TopLines method instead.
// If you only care about a subset of lines, use the ContainsLines method instead.
func (self *ViewDriver) Lines(matchers ...*TextMatcher) *ViewDriver {
self.validateMatchersPassed(matchers)
self.LineCount(EqualsInt(len(matchers)))
return self.assertLines(0, matchers...)
}
// asserts that the view has lines matching the given matchers. So if three matchers
// are passed, we only check the first three lines of the view.
// This method is convenient when you have a list of commits but you only want to
// assert on the first couple of commits.
func (self *ViewDriver) TopLines(matchers ...*TextMatcher) *ViewDriver {
self.validateMatchersPassed(matchers)
self.validateEnoughLines(matchers)
return self.assertLines(0, matchers...)
}
// Asserts on the visible lines of the view.
// Note, this assumes that the view's viewport is filled with lines
func (self *ViewDriver) VisibleLines(matchers ...*TextMatcher) *ViewDriver {
self.validateMatchersPassed(matchers)
self.validateVisibleLineCount(matchers)
// Get the origin of the view and offset that.
// Note that we don't do any retrying here so if we want to bring back retry logic
// we'll need to update this.
originY := self.getView().OriginY()
return self.assertLines(originY, matchers...)
}
// asserts that somewhere in the view there are consecutive lines matching the given matchers.
func (self *ViewDriver) ContainsLines(matchers ...*TextMatcher) *ViewDriver {
self.validateMatchersPassed(matchers)
self.validateEnoughLines(matchers)
self.t.assertWithRetries(func() (bool, string) {
content := self.getView().Buffer()
lines := strings.Split(content, "\n")
startIdx, endIdx := self.getSelectedRange()
for i := range len(lines) - len(matchers) + 1 {
matches := true
for j, matcher := range matchers {
checkIsSelected, matcher := matcher.checkIsSelected() // strip the IsSelected matcher out
lineIdx := i + j
ok, _ := matcher.test(lines[lineIdx])
if !ok {
matches = false
break
}
if checkIsSelected {
if lineIdx < startIdx || lineIdx > endIdx {
matches = false
break
}
}
}
if matches {
return true, ""
}
}
expectedContent := expectedContentFromMatchers(matchers)
return false, fmt.Sprintf(
"Expected the following to be contained in the staging panel:\n-----\n%s\n-----\nBut got:\n-----\n%s\n-----\nSelected range: %d-%d",
expectedContent,
content,
startIdx,
endIdx,
)
})
return self
}
func (self *ViewDriver) ContainsColoredText(fgColorStr string, text string) *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
view := self.getView()
ok := self.getView().ContainsColoredText(fgColorStr, text)
if !ok {
return false, fmt.Sprintf("expected view '%s' to contain colored text '%s' but it didn't", view.Name(), text)
}
return true, ""
})
return self
}
func (self *ViewDriver) DoesNotContainColoredText(fgColorStr string, text string) *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
view := self.getView()
ok := !self.getView().ContainsColoredText(fgColorStr, text)
if !ok {
return false, fmt.Sprintf("expected view '%s' to NOT contain colored text '%s' but it didn't", view.Name(), text)
}
return true, ""
})
return self
}
// asserts on the lines that are selected in the view. Don't use the `IsSelected` matcher with this because it's redundant.
func (self *ViewDriver) SelectedLines(matchers ...*TextMatcher) *ViewDriver {
self.validateMatchersPassed(matchers)
self.validateEnoughLines(matchers)
self.t.assertWithRetries(func() (bool, string) {
selectedLines := self.getSelectedLines()
selectedContent := strings.Join(selectedLines, "\n")
expectedContent := expectedContentFromMatchers(matchers)
if len(selectedLines) != len(matchers) {
return false, fmt.Sprintf("Expected the following to be selected:\n-----\n%s\n-----\nBut got:\n-----\n%s\n-----", expectedContent, selectedContent)
}
for i, line := range selectedLines {
checkIsSelected, matcher := matchers[i].checkIsSelected()
if checkIsSelected {
self.t.fail("You cannot use the IsSelected matcher with the SelectedLines method")
}
ok, message := matcher.test(line)
if !ok {
return false, fmt.Sprintf("Error: %s. Expected the following to be selected:\n-----\n%s\n-----\nBut got:\n-----\n%s\n-----", message, expectedContent, selectedContent)
}
}
return true, ""
})
return self
}
func (self *ViewDriver) validateMatchersPassed(matchers []*TextMatcher) {
if len(matchers) < 1 {
self.t.fail("'Lines' methods require at least one matcher to be passed as an argument. If you are trying to assert that there are no lines, use .IsEmpty()")
}
}
func (self *ViewDriver) validateEnoughLines(matchers []*TextMatcher) {
view := self.getView()
self.t.assertWithRetries(func() (bool, string) {
lines := view.BufferLines()
return len(lines) >= len(matchers), fmt.Sprintf("unexpected number of lines in view '%s'. Expected at least %d, got %d", view.Name(), len(matchers), len(lines))
})
}
// assumes the view's viewport is filled with lines
func (self *ViewDriver) validateVisibleLineCount(matchers []*TextMatcher) {
view := self.getView()
self.t.assertWithRetries(func() (bool, string) {
count := view.InnerHeight()
return count == len(matchers), fmt.Sprintf("unexpected number of visible lines in view '%s'. Expected exactly %d, got %d", view.Name(), len(matchers), count)
})
}
func (self *ViewDriver) assertLines(offset int, matchers ...*TextMatcher) *ViewDriver {
view := self.getView()
var expectedStartIdx, expectedEndIdx int
foundSelectionStart := false
foundSelectionEnd := false
expectedSelectedLines := []string{}
for matcherIndex, matcher := range matchers {
lineIdx := matcherIndex + offset
checkIsSelected, matcher := matcher.checkIsSelected()
if checkIsSelected {
if foundSelectionEnd {
self.t.fail("The IsSelected matcher can only be used on a contiguous range of lines.")
}
if !foundSelectionStart {
expectedStartIdx = lineIdx
foundSelectionStart = true
}
expectedSelectedLines = append(expectedSelectedLines, matcher.name())
expectedEndIdx = lineIdx
} else if foundSelectionStart {
foundSelectionEnd = true
}
}
for matcherIndex, matcher := range matchers {
lineIdx := matcherIndex + offset
expectSelected, matcher := matcher.checkIsSelected()
self.t.matchString(matcher, fmt.Sprintf("Unexpected content in view '%s'.", view.Name()),
func() string {
return view.BufferLines()[lineIdx]
},
)
// If any of the matchers care about the selection, we need to
// assert on the selection for each matcher.
if foundSelectionStart {
self.t.assertWithRetries(func() (bool, string) {
startIdx, endIdx := self.getSelectedRange()
selected := lineIdx >= startIdx && lineIdx <= endIdx
if (selected && expectSelected) || (!selected && !expectSelected) {
return true, ""
}
lines := self.getSelectedLines()
return false, fmt.Sprintf(
"Unexpected selection in view '%s'. Expected %s to be selected but got %s.\nExpected selected lines:\n---\n%s\n---\n\nActual selected lines:\n---\n%s\n---\n",
view.Name(),
formatLineRange(expectedStartIdx, expectedEndIdx),
formatLineRange(startIdx, endIdx),
strings.Join(expectedSelectedLines, "\n"),
strings.Join(lines, "\n"),
)
})
}
}
return self
}
func formatLineRange(from int, to int) string {
if from == to {
return "line " + fmt.Sprintf("%d", from)
}
return "lines " + fmt.Sprintf("%d-%d", from, to)
}
// asserts on the content of the view i.e. the stuff within the view's frame.
func (self *ViewDriver) Content(matcher *TextMatcher) *ViewDriver {
self.t.matchString(matcher, fmt.Sprintf("%s: Unexpected content.", self.context),
func() string {
return self.getView().Buffer()
},
)
return self
}
// asserts on the selected line of the view. If you are selecting a range,
// you should use the SelectedLines method instead.
func (self *ViewDriver) SelectedLine(matcher *TextMatcher) *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
selectedLineIdx := self.getSelectedLineIdx()
viewLines := self.getView().BufferLines()
if selectedLineIdx >= len(viewLines) {
return false, fmt.Sprintf("%s: Expected view to have at least %d lines, but it only has %d", self.context, selectedLineIdx+1, len(viewLines))
}
value := viewLines[selectedLineIdx]
return matcher.context(fmt.Sprintf("%s: Unexpected selected line.", self.context)).test(value)
})
return self
}
// asserts on the index of the selected line. 0 is the first index, representing the line at the top of the view.
func (self *ViewDriver) SelectedLineIdx(expected int) *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
actual := self.getView().SelectedLineIdx()
return expected == actual, fmt.Sprintf("%s: Expected selected line index to be %d, got %d", self.context, expected, actual)
})
return self
}
// focus the view (assumes the view is a side-view)
func (self *ViewDriver) Focus() *ViewDriver {
viewName := self.getView().Name()
type window struct {
name string
viewNames []string
}
windows := []window{
{name: "status", viewNames: []string{"status"}},
{name: "files", viewNames: []string{"files", "worktrees", "submodules"}},
{name: "branches", viewNames: []string{"localBranches", "remotes", "tags"}},
{name: "commits", viewNames: []string{"commits", "reflogCommits"}},
{name: "stash", viewNames: []string{"stash"}},
}
for windowIndex, window := range windows {
if lo.Contains(window.viewNames, viewName) {
tabIndex := lo.IndexOf(window.viewNames, viewName)
// jump to the desired window
self.t.press(self.t.keys.Universal.JumpToBlock[windowIndex])
// assert we're in the window before continuing
self.t.assertWithRetries(func() (bool, string) {
currentWindowName := self.t.gui.CurrentContext().GetWindowName()
// by convention the window is named after the first view in the window
return currentWindowName == window.name, fmt.Sprintf("Expected to be in window '%s', but was in '%s'", window.name, currentWindowName)
})
// switch to the desired tab
currentViewName := self.t.gui.CurrentContext().GetViewName()
currentViewTabIndex := lo.IndexOf(window.viewNames, currentViewName)
if tabIndex > currentViewTabIndex {
for range tabIndex - currentViewTabIndex {
self.t.press(self.t.keys.Universal.NextTab)
}
} else if tabIndex < currentViewTabIndex {
for range currentViewTabIndex - tabIndex {
self.t.press(self.t.keys.Universal.PrevTab)
}
}
// assert that we're now in the expected view
self.IsFocused()
return self
}
}
self.t.fail(fmt.Sprintf("Cannot focus view %s: Focus() method not implemented", viewName))
return self
}
// asserts that the view is focused
func (self *ViewDriver) IsFocused() *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
expected := self.getView().Name()
actual := self.t.gui.CurrentContext().GetView().Name()
return actual == expected, fmt.Sprintf("%s: Unexpected view focused. Expected %s, got %s", self.context, expected, actual)
})
return self
}
func (self *ViewDriver) Press(keyStr string) *ViewDriver {
self.IsFocused()
self.t.press(keyStr)
return self
}
func (self *ViewDriver) Delay() *ViewDriver {
self.t.Wait(self.t.inputDelay)
return self
}
// for use when typing or navigating, because in demos we want that to happen
// faster
func (self *ViewDriver) PressFast(keyStr string) *ViewDriver {
self.IsFocused()
self.t.pressFast(keyStr)
return self
}
func (self *ViewDriver) Click(x, y int) *ViewDriver {
offsetX, offsetY, _, _ := self.getView().Dimensions()
self.t.click(offsetX+1+x, offsetY+1+y)
return self
}
// i.e. pressing down arrow
func (self *ViewDriver) SelectNextItem() *ViewDriver {
return self.PressFast(self.t.keys.Universal.NextItem)
}
// i.e. pressing up arrow
func (self *ViewDriver) SelectPreviousItem() *ViewDriver {
return self.PressFast(self.t.keys.Universal.PrevItem)
}
// i.e. pressing '<'
func (self *ViewDriver) GotoTop() *ViewDriver {
return self.PressFast(self.t.keys.Universal.GotoTop)
}
// i.e. pressing space
func (self *ViewDriver) PressPrimaryAction() *ViewDriver {
return self.Press(self.t.keys.Universal.Select)
}
// i.e. pressing space
func (self *ViewDriver) PressEnter() *ViewDriver {
return self.Press(self.t.keys.Universal.Confirm)
}
// i.e. pressing tab
func (self *ViewDriver) PressTab() *ViewDriver {
return self.Press(self.t.keys.Universal.TogglePanel)
}
// i.e. pressing escape
func (self *ViewDriver) PressEscape() *ViewDriver {
return self.Press(self.t.keys.Universal.Return)
}
// this will look for a list item in the current panel and if it finds it, it will
// enter the keypresses required to navigate to it.
// The test will fail if:
// - the user is not in a list item
// - no list item is found containing the given text
// - multiple list items are found containing the given text in the initial page of items
func (self *ViewDriver) NavigateToLine(matcher *TextMatcher) *ViewDriver {
self.IsFocused()
view := self.getView()
lines := view.BufferLines()
matchIndex := -1
self.t.assertWithRetries(func() (bool, string) {
var matches []string
// first we look for a duplicate on the current screen. We won't bother looking beyond that though.
for i, line := range lines {
ok, _ := matcher.test(line)
if ok {
matches = append(matches, line)
matchIndex = i
}
}
if len(matches) > 1 {
return false, fmt.Sprintf("Found %d matches for `%s`, expected only a single match. Matching lines:\n%s", len(matches), matcher.name(), strings.Join(matches, "\n"))
}
return true, ""
})
// If no match was found, it could be that this is a view that renders only
// the visible lines. In that case, we jump to the top and then press
// down-arrow until we found the match. We simply return the first match we
// find, so we have no way to assert that there are no duplicates.
if matchIndex == -1 {
self.GotoTop()
matchIndex = len(lines)
}
selectedLineIdx := self.getSelectedLineIdx()
if selectedLineIdx == matchIndex {
return self.SelectedLine(matcher)
}
// At this point we can't just take the difference of selected and matched
// index and press up or down arrow this many times. The reason is that
// there might be section headers between those lines, and these will be
// skipped when pressing up or down arrow. So we must keep pressing the
// arrow key in a loop, and check after each one whether we now reached the
// target line.
var maxNumKeyPresses int
var keyPress func()
if selectedLineIdx < matchIndex {
maxNumKeyPresses = matchIndex - selectedLineIdx
keyPress = func() { self.SelectNextItem() }
} else {
maxNumKeyPresses = selectedLineIdx - matchIndex
keyPress = func() { self.SelectPreviousItem() }
}
for range maxNumKeyPresses {
keyPress()
idx := self.getSelectedLineIdx()
// It is important to use view.BufferLines() here and not lines, because it
// could change with every keypress.
if ok, _ := matcher.test(view.BufferLines()[idx]); ok {
return self
}
}
self.t.fail(fmt.Sprintf("Could not navigate to item matching: %s. Lines:\n%s", matcher.name(), strings.Join(view.BufferLines(), "\n")))
return self
}
// returns true if the view is a list view and it contains no items
func (self *ViewDriver) IsEmpty() *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
actual := strings.TrimSpace(self.getView().Buffer())
return actual == "", fmt.Sprintf("%s: Unexpected content in view: expected no content. Content: %s", self.context, actual)
})
return self
}
func (self *ViewDriver) LineCount(matcher *IntMatcher) *ViewDriver {
view := self.getView()
self.t.assertWithRetries(func() (bool, string) {
lineCount := self.getLineCount()
ok, _ := matcher.test(lineCount)
return ok, fmt.Sprintf("unexpected number of lines in view '%s'. Expected %s, got %d", view.Name(), matcher.name(), lineCount)
})
return self
}
func (self *ViewDriver) getLineCount() int {
// can't rely entirely on view.BufferLines because it returns 1 even if there's nothing in the view
if strings.TrimSpace(self.getView().Buffer()) == "" {
return 0
}
view := self.getView()
return len(view.BufferLines())
}
func (self *ViewDriver) IsVisible() *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
return self.getView().Visible, fmt.Sprintf("%s: Expected view to be visible, but it was not", self.context)
})
return self
}
func (self *ViewDriver) IsInvisible() *ViewDriver {
self.t.assertWithRetries(func() (bool, string) {
return !self.getView().Visible, fmt.Sprintf("%s: Expected view to be invisible, but it was not", self.context)
})
return self
}
// will filter or search depending on whether the view supports filtering/searching
func (self *ViewDriver) FilterOrSearch(text string) *ViewDriver {
self.IsFocused()
self.Press(self.t.keys.Universal.StartSearch).
Tap(func() {
self.t.ExpectSearch().
Clear().
Type(text).
Confirm()
self.t.Views().Search().IsVisible().Content(Contains(fmt.Sprintf("matches for '%s'", text)))
})
return self
}
func (self *ViewDriver) SetCaption(caption string) *ViewDriver {
self.t.gui.SetCaption(caption)
return self
}
func (self *ViewDriver) SetCaptionPrefix(prefix string) *ViewDriver {
self.t.gui.SetCaptionPrefix(prefix)
return self
}
func (self *ViewDriver) Wait(milliseconds int) *ViewDriver {
if !self.t.gui.Headless() {
self.t.Wait(milliseconds)
}
return self
}
// for when you want to make some assertion unrelated to the current view
// without breaking the method chain
func (self *ViewDriver) Tap(f func()) *ViewDriver {
f()
return self
}
// This purely exists as a convenience method for those who hate the trailing periods in multi-line method chains
func (self *ViewDriver) Self() *ViewDriver {
return self
}
func expectedContentFromMatchers(matchers []*TextMatcher) string {
return strings.Join(lo.Map(matchers, func(matcher *TextMatcher, _ int) string {
return matcher.name()
}), "\n")
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/search_driver.go | pkg/integration/components/search_driver.go | package components
// TODO: soft-code this
const ClearKey = "<c-u>"
type SearchDriver struct {
t *TestDriver
}
func (self *SearchDriver) getViewDriver() *ViewDriver {
return self.t.Views().Search()
}
// asserts on the text initially present in the prompt
func (self *SearchDriver) InitialText(expected *TextMatcher) *SearchDriver {
self.getViewDriver().Content(expected)
return self
}
func (self *SearchDriver) Type(value string) *SearchDriver {
self.t.typeContent(value)
return self
}
func (self *SearchDriver) Clear() *SearchDriver {
self.t.press(ClearKey)
return self
}
func (self *SearchDriver) Confirm() {
self.getViewDriver().PressEnter()
}
func (self *SearchDriver) Cancel() {
self.getViewDriver().PressEscape()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/int_matcher.go | pkg/integration/components/int_matcher.go | package components
import (
"fmt"
)
type IntMatcher struct {
*Matcher[int]
}
func (self *IntMatcher) EqualsInt(target int) *IntMatcher {
self.appendRule(matcherRule[int]{
name: fmt.Sprintf("equals %d", target),
testFn: func(value int) (bool, string) {
return value == target, fmt.Sprintf("Expected %d to equal %d", value, target)
},
})
return self
}
func (self *IntMatcher) GreaterThan(target int) *IntMatcher {
self.appendRule(matcherRule[int]{
name: fmt.Sprintf("greater than %d", target),
testFn: func(value int) (bool, string) {
return value > target, fmt.Sprintf("Expected %d to greater than %d", value, target)
},
})
return self
}
func (self *IntMatcher) LessThan(target int) *IntMatcher {
self.appendRule(matcherRule[int]{
name: fmt.Sprintf("less than %d", target),
testFn: func(value int) (bool, string) {
return value < target, fmt.Sprintf("Expected %d to less than %d", value, target)
},
})
return self
}
func AnyInt() *IntMatcher {
return &IntMatcher{Matcher: &Matcher[int]{}}
}
func EqualsInt(target int) *IntMatcher {
return AnyInt().EqualsInt(target)
}
func GreaterThan(target int) *IntMatcher {
return AnyInt().GreaterThan(target)
}
func LessThan(target int) *IntMatcher {
return AnyInt().LessThan(target)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/random.go | pkg/integration/components/random.go | package components
var RandomCommitMessages = []string{
`Refactor HTTP client for better error handling`,
`Integrate pagination in user listings`,
`Fix incorrect type in updateUser function`,
`Create initial setup for postgres database`,
`Add unit tests for authentication service`,
`Improve efficiency of sorting algorithm in util package`,
`Resolve intermittent test failure in CartTest`,
`Introduce cache layer for product images`,
`Revamp User Interface of the settings page`,
`Remove deprecated uses of api endpoints`,
`Ensure proper escaping of SQL queries`,
`Implement feature flag for dark mode`,
`Add functionality for users to reset password`,
`Optimize performance of image loading on home screen`,
`Correct argument type in the sendEmail function`,
`Merge feature branch 'add-payment-gateway'`,
`Add validation to signup form fields`,
`Refactor User model to include middle name`,
`Update README with new setup instructions`,
`Extend session expiry time to 24 hours`,
`Implement rate limiting on login attempts`,
`Add sorting feature to product listing page`,
`Refactor logic in Lazygit Diff view`,
`Optimize Lazygit startup time`,
`Fix typos in documentation`,
`Move global variables to environment config`,
`Upgrade Rails version to 6.1.4`,
`Refactor user notifications system`,
`Implement user blocking functionality`,
`Improve Dockerfile for more efficient builds`,
`Introduce Redis for session management`,
`Ensure CSRF protection for all forms`,
`Implement bulk delete feature in admin panel`,
`Harden security of user password storage`,
`Resolve race condition in transaction handling`,
`Migrate legacy codebase to Typescript`,
`Update UX of password reset feature`,
`Add internationalization support for German`,
`Enhance logging in production environment`,
`Remove hardcoded values from payment module`,
`Introduce retry mechanism in network calls`,
`Handle edge case for zero quantity in cart`,
`Revamp error handling in user registration`,
`Replace deprecated lifecycle methods in React components`,
`Update styles according to new design guidelines`,
`Handle database connection failures gracefully`,
`Ensure atomicity of transactions in payment system`,
`Refactor session management using JWT`,
`Enhance user search with fuzzy matching`,
`Move constants to a separate config file`,
`Add TypeScript types to User module`,
`Implement automated backups for database`,
`Fix broken links on the help page`,
`Add end-to-end tests for checkout flow`,
`Add loading indicators to improve UX`,
`Improve accessibility of site navigation`,
`Refactor error messages for better clarity`,
`Enable gzip compression for faster page loads`,
`Set up CI/CD pipeline using GitHub actions`,
`Add a user-friendly 404 page`,
`Implement OAuth login with Google`,
`Resolve dependency conflicts in package.json`,
`Add proper alt text to all images for SEO`,
`Implement comment moderation feature`,
`Fix double encoding issue in URL parameters`,
`Resolve flickering issue in animation`,
`Update dependencies to latest stable versions`,
`Set proper cache headers for static assets`,
`Add structured data for better SEO`,
`Refactor to remove circular dependencies`,
`Add feature to report inappropriate content`,
`Implement mobile-friendly navigation menu`,
`Update privacy policy to comply with GDPR`,
`Fix memory leak issue in event listeners`,
`Improve form validation feedback for user`,
`Implement API versioning`,
`Improve resilience of system by adding circuit breaker`,
`Add sitemap.xml for better search engine indexing`,
`Set up performance monitoring with New Relic`,
`Introduce service worker for offline support`,
`Enhance email notifications with HTML templates`,
`Ensure all pages are responsive across devices`,
`Create helper functions to reduce code duplication`,
`Add 'remember me' feature to login`,
`Increase test coverage for User model`,
`Refactor error messages into a separate module`,
`Optimize images for faster loading`,
`Ensure correct HTTP status codes for all responses`,
`Implement auto-save feature in post editor`,
`Update user guide with new screenshots`,
`Implement load testing using Gatling`,
`Add keyboard shortcuts for commonly used actions`,
`Set up staging environment similar to production`,
`Ensure all forms use POST method for data submission`,
`Implement soft delete for user accounts`,
`Add Webpack for asset bundling`,
`Handle session timeout gracefully`,
`Remove unused code and libraries`,
`Integrate support for markdown in user posts`,
`Fix bug in timezone conversion.`,
}
type RandomFile struct {
Name string
Content string
}
var RandomFiles = []RandomFile{
{Name: `http_client.go`, Content: `package httpclient`},
{Name: `user_listings.go`, Content: `package listings`},
{Name: `user_service.go`, Content: `package service`},
{Name: `database_setup.sql`, Content: `CREATE TABLE`},
{Name: `authentication_test.go`, Content: `package auth_test`},
{Name: `utils/sorting.go`, Content: `package utils`},
{Name: `tests/cart_test.go`, Content: `package tests`},
{Name: `cache/product_images.go`, Content: `package cache`},
{Name: `ui/settings_page.jsx`, Content: `import React`},
{Name: `api/deprecated_endpoints.go`, Content: `package api`},
{Name: `db/sql_queries.go`, Content: `package db`},
{Name: `features/dark_mode.go`, Content: `package features`},
{Name: `user/password_reset.go`, Content: `package user`},
{Name: `performance/image_loading.go`, Content: `package performance`},
{Name: `email/send_email.go`, Content: `package email`},
{Name: `merge/payment_gateway.go`, Content: `package merge`},
{Name: `forms/signup_validation.go`, Content: `package forms`},
{Name: `models/user.go`, Content: `package models`},
{Name: `README.md`, Content: `# Project`},
{Name: `config/session.go`, Content: `package config`},
{Name: `security/rate_limit.go`, Content: `package security`},
{Name: `product/sort_list.go`, Content: `package product`},
{Name: `lazygit/diff_view.go`, Content: `package lazygit`},
{Name: `performance/lazygit.go`, Content: `package performance`},
{Name: `docs/documentation.go`, Content: `package docs`},
{Name: `config/global_variables.go`, Content: `package config`},
{Name: `Gemfile`, Content: `source 'https://rubygems.org'`},
{Name: `notification/user_notification.go`, Content: `package notification`},
{Name: `user/blocking.go`, Content: `package user`},
{Name: `Dockerfile`, Content: `FROM ubuntu:18.04`},
{Name: `redis/session_manager.go`, Content: `package redis`},
{Name: `security/csrf_protection.go`, Content: `package security`},
{Name: `admin/bulk_delete.go`, Content: `package admin`},
{Name: `security/password_storage.go`, Content: `package security`},
{Name: `transactions/transaction_handling.go`, Content: `package transactions`},
{Name: `migrations/typescript_migration.go`, Content: `package migrations`},
{Name: `ui/password_reset.jsx`, Content: `import React`},
{Name: `i18n/german.go`, Content: `package i18n`},
{Name: `logging/production_logging.go`, Content: `package logging`},
{Name: `payment/hardcoded_values.go`, Content: `package payment`},
{Name: `network/retry.go`, Content: `package network`},
{Name: `cart/zero_quantity.go`, Content: `package cart`},
{Name: `registration/error_handling.go`, Content: `package registration`},
{Name: `components/deprecated_methods.jsx`, Content: `import React`},
{Name: `styles/new_guidelines.css`, Content: `.class {}`},
{Name: `db/connection_failure.go`, Content: `package db`},
{Name: `payment/transaction_atomicity.go`, Content: `package payment`},
{Name: `session/jwt_management.go`, Content: `package session`},
{Name: `search/fuzzy_matching.go`, Content: `package search`},
{Name: `config/constants.go`, Content: `package config`},
{Name: `models/user_types.go`, Content: `package models`},
{Name: `backup/database_backup.go`, Content: `package backup`},
{Name: `help_page/links.go`, Content: `package help_page`},
{Name: `tests/checkout_test.sql`, Content: `DELETE ALL TABLES;`},
{Name: `ui/loading_indicator.jsx`, Content: `import React`},
{Name: `navigation/site_navigation.go`, Content: `package navigation`},
{Name: `error/error_messages.go`, Content: `package error`},
{Name: `performance/gzip_compression.go`, Content: `package performance`},
{Name: `.github/workflows/ci.yml`, Content: `name: CI`},
{Name: `pages/404.html`, Content: `<html></html>`},
{Name: `oauth/google_login.go`, Content: `package oauth`},
{Name: `package.json`, Content: `{}`},
{Name: `seo/alt_text.go`, Content: `package seo`},
{Name: `moderation/comment_moderation.go`, Content: `package moderation`},
{Name: `url/double_encoding.go`, Content: `package url`},
{Name: `animation/flickering.go`, Content: `package animation`},
{Name: `upgrade_dependencies.sh`, Content: `#!/bin/sh`},
{Name: `security/csrf_protection2.go`, Content: `package security`},
{Name: `admin/bulk_delete2.go`, Content: `package admin`},
{Name: `security/password_storage2.go`, Content: `package security`},
{Name: `transactions/transaction_handling2.go`, Content: `package transactions`},
{Name: `migrations/typescript_migration2.go`, Content: `package migrations`},
{Name: `ui/password_reset2.jsx`, Content: `import React`},
{Name: `i18n/german2.go`, Content: `package i18n`},
{Name: `logging/production_logging2.go`, Content: `package logging`},
{Name: `payment/hardcoded_values2.go`, Content: `package payment`},
{Name: `network/retry2.go`, Content: `package network`},
{Name: `cart/zero_quantity2.go`, Content: `package cart`},
{Name: `registration/error_handling2.go`, Content: `package registration`},
{Name: `components/deprecated_methods2.jsx`, Content: `import React`},
{Name: `styles/new_guidelines2.css`, Content: `.class {}`},
{Name: `db/connection_failure2.go`, Content: `package db`},
{Name: `payment/transaction_atomicity2.go`, Content: `package payment`},
{Name: `session/jwt_management2.go`, Content: `package session`},
{Name: `search/fuzzy_matching2.go`, Content: `package search`},
{Name: `config/constants2.go`, Content: `package config`},
{Name: `models/user_types2.go`, Content: `package models`},
{Name: `backup/database_backup2.go`, Content: `package backup`},
{Name: `help_page/links2.go`, Content: `package help_page`},
{Name: `tests/checkout_test2.go`, Content: `package tests`},
{Name: `ui/loading_indicator2.jsx`, Content: `import React`},
{Name: `navigation/site_navigation2.go`, Content: `package navigation`},
{Name: `error/error_messages2.go`, Content: `package error`},
{Name: `performance/gzip_compression2.go`, Content: `package performance`},
{Name: `.github/workflows/ci2.yml`, Content: `name: CI`},
{Name: `pages/4042.html`, Content: `<html></html>`},
{Name: `oauth/google_login2.go`, Content: `package oauth`},
{Name: `package2.json`, Content: `{}`},
{Name: `seo/alt_text2.go`, Content: `package seo`},
{Name: `moderation/comment_moderation2.go`, Content: `package moderation`},
}
var RandomFileContents = []string{
`package main
import (
"bytes"
"fmt"
"go/format"
"io/fs"
"os"
"strings"
"github.com/samber/lo"
)
func main() {
code := generateCode()
formattedCode, err := format.Source(code)
if err != nil {
panic(err)
}
if err := os.WriteFile("test_list.go", formattedCode, 0o644); err != nil {
panic(err)
}
}
`,
`
package tests
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/jesseduffield/generics/set"
"github.com/jesseduffield/lazycore/pkg/utils"
"github.com/jesseduffield/lazygit/pkg/integration/components"
"github.com/samber/lo"
)
func GetTests() []*components.IntegrationTest {
// first we ensure that each test in this directory has actually been added to the above list.
testCount := 0
testNamesSet := set.NewFromSlice(lo.Map(
tests,
func(test *components.IntegrationTest, _ int) string {
return test.Name()
},
))
}
`,
`
package components
import (
"os"
"strconv"
"strings"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/config"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
// IntegrationTest describes an integration test that will be run against the lazygit gui.
// our unit tests will use this description to avoid a panic caused by attempting
// to get the test's name via it's file's path.
const unitTestDescription = "test test"
const (
defaultWidth = 100
defaultHeight = 100
)
`,
`package components
import (
"fmt"
"time"
"github.com/atotto/clipboard"
"github.com/jesseduffield/lazygit/pkg/config"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
)
type TestDriver struct {
gui integrationTypes.GuiDriver
keys config.KeybindingConfig
inputDelay int
*assertionHelper
shell *Shell
}
func NewTestDriver(gui integrationTypes.GuiDriver, shell *Shell, keys config.KeybindingConfig, inputDelay int) *TestDriver {
return &TestDriver{
gui: gui,
keys: keys,
inputDelay: inputDelay,
assertionHelper: &assertionHelper{gui: gui},
shell: shell,
}
}
// key is something like 'w' or '<space>'. It's best not to pass a direct value,
// but instead to go through the default user config to get a more meaningful key name
func (self *TestDriver) press(keyStr string) {
self.SetCaption(fmt.Sprintf("Pressing %s", keyStr))
self.gui.PressKey(keyStr)
self.Wait(self.inputDelay)
}
`,
`package updates
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/go-errors/errors"
"github.com/kardianos/osext"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/constants"
"github.com/jesseduffield/lazygit/pkg/utils"
)
// Updater checks for updates and does updates
type Updater struct {
*common.Common
Config config.AppConfigurer
OSCommand *oscommands.OSCommand
}
// Updaterer implements the check and update methods
type Updaterer interface {
CheckForNewUpdate()
Update()
}
`,
`
package utils
import (
"fmt"
"regexp"
"strings"
)
// IsValidEmail checks if an email address is valid
func IsValidEmail(email string) bool {
// Using a regex pattern to validate email addresses
// This is a simple example and might not cover all edge cases
emailPattern := ` + "`" + `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` + "`" + `
match, _ := regexp.MatchString(emailPattern, email)
return match
}
`,
`
package main
import (
"fmt"
"net/http"
"time"
"github.com/jesseduffield/lazygit/pkg/utils"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, the current time is: %s", time.Now().Format(time.RFC3339))
})
port := 8080
utils.PrintMessage(fmt.Sprintf("Server is listening on port %d", port))
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
`,
`
package logging
import (
"fmt"
"os"
"time"
)
// LogMessage represents a log message with its timestamp
type LogMessage struct {
Timestamp time.Time
Message string
}
// Log writes a message to the log file along with a timestamp
func Log(message string) {
logFile, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("Error opening log file:", err)
return
}
defer logFile.Close()
logEntry := LogMessage{
Timestamp: time.Now(),
Message: message,
}
logLine := fmt.Sprintf("[%s] %s\n", logEntry.Timestamp.Format("2006-01-02 15:04:05"), logEntry.Message)
_, err = logFile.WriteString(logLine)
if err != nil {
fmt.Println("Error writing to log file:", err)
}
}
`,
`
package encryption
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
)
// Encrypt encrypts a plaintext using AES-GCM encryption
func Encrypt(key []byte, plaintext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesGCM.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
return append(nonce, ciphertext...), nil
}
`,
}
var RandomBranchNames = []string{
"hotfix/fix-bug",
"r-u-fkn-srs",
"iserlohn-build",
"hotfix/fezzan-corridor",
"terra-investigation",
"quash-rebellion",
"feature/attack-on-odin",
"feature/peace-time",
"feature/repair-brunhild",
"feature/iserlohn-backdoor",
"bugfix/resolve-crash",
"enhancement/improve-performance",
"experimental/new-feature",
"release/v1.0.0",
"release/v2.0.0",
"chore/update-dependencies",
"docs/add-readme",
"refactor/cleanup-code",
"style/update-css",
"test/add-unit-tests",
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/components/common.go | pkg/integration/components/common.go | package components
import "fmt"
// for running common actions
type Common struct {
t *TestDriver
}
func (self *Common) ContinueMerge() {
self.t.GlobalPress(self.t.keys.Universal.CreateRebaseOptionsMenu)
self.t.ExpectPopup().Menu().
Title(Equals("Rebase options")).
Select(Contains("continue")).
Confirm()
}
func (self *Common) ContinueRebase() {
self.ContinueMerge()
}
func (self *Common) AbortRebase() {
self.t.GlobalPress(self.t.keys.Universal.CreateRebaseOptionsMenu)
self.t.ExpectPopup().Menu().
Title(Equals("Rebase options")).
Select(Contains("abort")).
Confirm()
}
func (self *Common) AbortMerge() {
self.t.GlobalPress(self.t.keys.Universal.CreateRebaseOptionsMenu)
self.t.ExpectPopup().Menu().
Title(Equals("Merge options")).
Select(Contains("abort")).
Confirm()
}
func (self *Common) AcknowledgeConflicts() {
self.t.ExpectPopup().Menu().
Title(Equals("Conflicts!")).
Select(Contains("View conflicts")).
Confirm()
}
func (self *Common) ContinueOnConflictsResolved(command string) {
self.t.ExpectPopup().Confirmation().
Title(Equals("Continue")).
Content(Contains(fmt.Sprintf("All merge conflicts resolved. Continue the %s?", command))).
Confirm()
}
func (self *Common) ConfirmDiscardLines() {
self.t.ExpectPopup().Confirmation().
Title(Equals("Discard change")).
Content(Contains("Are you sure you want to discard this change")).
Confirm()
}
func (self *Common) SelectPatchOption(matcher *TextMatcher) {
self.t.GlobalPress(self.t.keys.Universal.CreatePatchOptionsMenu)
self.t.ExpectPopup().Menu().Title(Equals("Patch options")).Select(matcher).Confirm()
}
func (self *Common) ResetBisect() {
self.t.Views().Commits().
Focus().
Press(self.t.keys.Commits.ViewBisectOptions).
Tap(func() {
self.t.ExpectPopup().Menu().
Title(Equals("Bisect")).
Select(Contains("Reset bisect")).
Confirm()
self.t.ExpectPopup().Confirmation().
Title(Equals("Reset 'git bisect'")).
Content(Contains("Are you sure you want to reset 'git bisect'?")).
Confirm()
})
}
func (self *Common) ResetCustomPatch() {
self.t.GlobalPress(self.t.keys.Universal.CreatePatchOptionsMenu)
self.t.ExpectPopup().Menu().
Title(Equals("Patch options")).
Select(Contains("Reset patch")).
Confirm()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/types/types.go | pkg/integration/types/types.go | package types
import (
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazygit/pkg/commands/models"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/gui/types"
)
// these interfaces are used by the gui package so that it knows what it needs
// to provide to a test in order for the test to run.
type IntegrationTest interface {
Run(GuiDriver)
SetupConfig(config *config.AppConfig)
RequiresHeadless() bool
// width and height when running headless
HeadlessDimensions() (int, int)
// If true, we are recording/replaying a demo
IsDemo() bool
}
// this is the interface through which our integration tests interact with the lazygit gui
type GuiDriver interface {
PressKey(string)
Click(int, int)
Keys() config.KeybindingConfig
CurrentContext() types.Context
ContextForView(viewName string) types.Context
Fail(message string)
// These two log methods are for the sake of debugging while testing. There's no need to actually
// commit any logging.
// logs to the normal place that you log to i.e. viewable with `lazygit --logs`
Log(message string)
// logs in the actual UI (in the commands panel)
LogUI(message string)
CheckedOutRef() *models.Branch
// the view that appears to the right of the side panel
MainView() *gocui.View
// the other view that sometimes appears to the right of the side panel
// e.g. when we're showing both staged and unstaged changes
SecondaryView() *gocui.View
View(viewName string) *gocui.View
SetCaption(caption string)
SetCaptionPrefix(prefix string)
// Pop the next toast that was displayed; returns nil if there was none
NextToast() *string
CheckAllToastsAcknowledged()
Headless() bool
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/clients/go_test.go | pkg/integration/clients/go_test.go | //go:build !windows
package clients
// This file allows you to use `go test` to run integration tests.
// See pkg/integration/README.md for more info.
import (
"bytes"
"errors"
"io"
"os"
"os/exec"
"testing"
"github.com/creack/pty"
"github.com/jesseduffield/lazycore/pkg/utils"
"github.com/jesseduffield/lazygit/pkg/integration/components"
"github.com/jesseduffield/lazygit/pkg/integration/tests"
"github.com/stretchr/testify/assert"
)
func TestIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration tests in short mode")
}
parallelTotal := tryConvert(os.Getenv("PARALLEL_TOTAL"), 1)
parallelIndex := tryConvert(os.Getenv("PARALLEL_INDEX"), 0)
raceDetector := os.Getenv("LAZYGIT_RACE_DETECTOR") != ""
// LAZYGIT_GOCOVERDIR is the directory where we write coverage files to. If this directory
// is defined, go binaries built with the -cover flag will write coverage files to
// to it.
codeCoverageDir := os.Getenv("LAZYGIT_GOCOVERDIR")
testNumber := 0
err := components.RunTests(components.RunTestArgs{
Tests: tests.GetTests(utils.GetLazyRootDirectory()),
Logf: t.Logf,
RunCmd: runCmdHeadless,
TestWrapper: func(test *components.IntegrationTest, f func() error) {
defer func() { testNumber += 1 }()
if testNumber%parallelTotal != parallelIndex {
return
}
t.Run(test.Name(), func(t *testing.T) {
t.Parallel()
err := f()
assert.NoError(t, err)
})
},
Sandbox: false,
WaitForDebugger: false,
RaceDetector: raceDetector,
CodeCoverageDir: codeCoverageDir,
InputDelay: 0,
// Allow two attempts at each test to get around flakiness
MaxAttempts: 2,
})
assert.NoError(t, err)
}
func runCmdHeadless(cmd *exec.Cmd) (int, error) {
cmd.Env = append(
cmd.Env,
"LAZYGIT_HEADLESS=true",
"TERM=xterm",
)
// not writing stderr to the pty because we want to capture a panic if
// there is one. But some commands will not be in tty mode if stderr is
// not a terminal. We'll need to keep an eye out for that.
stderr := new(bytes.Buffer)
cmd.Stderr = stderr
// these rows and columns are ignored because internally we use tcell's
// simulation screen. However we still need the pty for the sake of
// running other commands in a pty.
f, err := pty.StartWithSize(cmd, &pty.Winsize{Rows: 300, Cols: 300})
if err != nil {
return -1, err
}
_, _ = io.Copy(io.Discard, f)
if cmd.Wait() != nil {
_ = f.Close()
// return an error with the stderr output
return cmd.Process.Pid, errors.New(stderr.String())
}
return cmd.Process.Pid, f.Close()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/clients/tui.go | pkg/integration/clients/tui.go | package clients
import (
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/jesseduffield/gocui"
"github.com/jesseduffield/lazycore/pkg/utils"
"github.com/jesseduffield/lazygit/pkg/gui"
"github.com/jesseduffield/lazygit/pkg/gui/style"
"github.com/jesseduffield/lazygit/pkg/integration/components"
"github.com/jesseduffield/lazygit/pkg/integration/tests"
"github.com/samber/lo"
)
// This program lets you run integration tests from a TUI. See pkg/integration/README.md for more info.
var SLOW_INPUT_DELAY = 600
func RunTUI(raceDetector bool) {
rootDir := utils.GetLazyRootDirectory()
testDir := filepath.Join(rootDir, "test", "integration")
app := newApp(testDir)
app.loadTests()
g, err := gocui.NewGui(gocui.NewGuiOpts{
OutputMode: gocui.OutputTrue,
RuneReplacements: gui.RuneReplacements,
})
if err != nil {
log.Panicln(err)
}
g.Cursor = false
app.g = g
g.SetManagerFunc(app.layout)
if err := g.SetKeybinding("list", gocui.KeyArrowUp, gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
if app.itemIdx > 0 {
app.itemIdx--
}
listView, err := g.View("list")
if err != nil {
return err
}
listView.FocusPoint(0, app.itemIdx, true)
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", gocui.KeyArrowDown, gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
if app.itemIdx < len(app.filteredTests)-1 {
app.itemIdx++
}
listView, err := g.View("list")
if err != nil {
return err
}
listView.FocusPoint(0, app.itemIdx, true)
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", 'q', gocui.ModNone, quit); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", 's', gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
currentTest := app.getCurrentTest()
if currentTest == nil {
return nil
}
suspendAndRunTest(currentTest, true, false, raceDetector, 0)
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", gocui.KeyEnter, gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
currentTest := app.getCurrentTest()
if currentTest == nil {
return nil
}
suspendAndRunTest(currentTest, false, false, raceDetector, 0)
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", 't', gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
currentTest := app.getCurrentTest()
if currentTest == nil {
return nil
}
suspendAndRunTest(currentTest, false, false, raceDetector, SLOW_INPUT_DELAY)
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", 'd', gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
currentTest := app.getCurrentTest()
if currentTest == nil {
return nil
}
suspendAndRunTest(currentTest, false, true, raceDetector, 0)
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", 'o', gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
currentTest := app.getCurrentTest()
if currentTest == nil {
return nil
}
cmd := exec.Command("sh", "-c", fmt.Sprintf("code -r pkg/integration/tests/%s.go", currentTest.Name()))
if err := cmd.Run(); err != nil {
return err
}
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", 'O', gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
currentTest := app.getCurrentTest()
if currentTest == nil {
return nil
}
cmd := exec.Command("sh", "-c", fmt.Sprintf("code test/_results/%s", currentTest.Name()))
if err := cmd.Run(); err != nil {
return err
}
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("list", '/', gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
app.filtering = true
if _, err := g.SetCurrentView("editor"); err != nil {
return err
}
editorView, err := g.View("editor")
if err != nil {
return err
}
editorView.Clear()
return nil
}); err != nil {
log.Panicln(err)
}
// not using the editor yet, but will use it to help filter the list
if err := g.SetKeybinding("editor", gocui.KeyEsc, gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
app.filtering = false
if _, err := g.SetCurrentView("list"); err != nil {
return err
}
app.filteredTests = app.allTests
app.renderTests()
app.editorView.TextArea.Clear()
app.editorView.Clear()
app.editorView.Reset()
return nil
}); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("editor", gocui.KeyEnter, gocui.ModNone, func(*gocui.Gui, *gocui.View) error {
app.filtering = false
if _, err := g.SetCurrentView("list"); err != nil {
return err
}
app.renderTests()
return nil
}); err != nil {
log.Panicln(err)
}
err = g.MainLoop()
g.Close()
if errors.Is(err, gocui.ErrQuit) {
return
}
log.Panicln(err)
}
type app struct {
allTests []*components.IntegrationTest
filteredTests []*components.IntegrationTest
itemIdx int
testDir string
filtering bool
g *gocui.Gui
listView *gocui.View
editorView *gocui.View
}
func newApp(testDir string) *app {
return &app{testDir: testDir, allTests: tests.GetTests(utils.GetLazyRootDirectory())}
}
func (self *app) getCurrentTest() *components.IntegrationTest {
self.adjustCursor()
if len(self.filteredTests) > 0 {
return self.filteredTests[self.itemIdx]
}
return nil
}
func (self *app) loadTests() {
self.filteredTests = self.allTests
self.adjustCursor()
}
func (self *app) adjustCursor() {
self.itemIdx = utils.Clamp(self.itemIdx, 0, len(self.filteredTests)-1)
}
func (self *app) filterWithString(needle string) {
if needle == "" {
self.filteredTests = self.allTests
} else {
self.filteredTests = lo.Filter(self.allTests, func(test *components.IntegrationTest, _ int) bool {
return strings.Contains(test.Name(), needle)
})
}
self.renderTests()
self.g.Update(func(g *gocui.Gui) error { return nil })
}
func (self *app) renderTests() {
self.listView.Clear()
for _, test := range self.filteredTests {
fmt.Fprintln(self.listView, test.Name())
}
}
func (self *app) 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 {
self.filterWithString(v.TextArea.GetContent())
}
return matched
}
}
func suspendAndRunTest(test *components.IntegrationTest, sandbox bool, waitForDebugger bool, raceDetector bool, inputDelay int) {
if err := gocui.Screen.Suspend(); err != nil {
panic(err)
}
runTuiTest(test, sandbox, waitForDebugger, raceDetector, inputDelay)
fmt.Fprintf(os.Stdout, "\n%s", style.FgGreen.Sprint("press enter to return"))
_, _ = fmt.Scanln() // wait for enter press
if err := gocui.Screen.Resume(); err != nil {
panic(err)
}
}
func (self *app) layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
descriptionViewHeight := 7
keybindingsViewHeight := 3
editorViewHeight := 3
if !self.filtering {
editorViewHeight = 0
} else {
descriptionViewHeight = 0
keybindingsViewHeight = 0
}
g.Cursor = self.filtering
g.FgColor = gocui.ColorGreen
listView, err := g.SetView("list", 0, 0, maxX-1, maxY-descriptionViewHeight-keybindingsViewHeight-editorViewHeight-1, 0)
if err != nil {
if !errors.Is(err, gocui.ErrUnknownView) {
return err
}
if self.listView == nil {
self.listView = listView
}
listView.Highlight = true
listView.SelBgColor = gocui.ColorBlue
self.renderTests()
listView.Title = "Tests"
listView.FgColor = gocui.ColorDefault
if _, err := g.SetCurrentView("list"); err != nil {
return err
}
}
descriptionView, err := g.SetViewBeneath("description", "list", descriptionViewHeight)
if err != nil {
if !errors.Is(err, gocui.ErrUnknownView) {
return err
}
descriptionView.Title = "Test description"
descriptionView.Wrap = true
descriptionView.FgColor = gocui.ColorDefault
}
keybindingsView, err := g.SetViewBeneath("keybindings", "description", keybindingsViewHeight)
if err != nil {
if !errors.Is(err, gocui.ErrUnknownView) {
return err
}
keybindingsView.Title = "Keybindings"
keybindingsView.Wrap = true
keybindingsView.FgColor = gocui.ColorDefault
fmt.Fprintln(keybindingsView, "up/down: navigate, enter: run test, t: run test slow, s: sandbox, d: debug test, o: open test file, shift+o: open test snapshot directory, forward-slash: filter")
}
editorView, err := g.SetViewBeneath("editor", "keybindings", editorViewHeight)
if err != nil {
if !errors.Is(err, gocui.ErrUnknownView) {
return err
}
if self.editorView == nil {
self.editorView = editorView
}
editorView.Title = "Filter"
editorView.FgColor = gocui.ColorDefault
editorView.Editable = true
editorView.Editor = gocui.EditorFunc(self.wrapEditor(gocui.SimpleEditor))
}
currentTest := self.getCurrentTest()
if currentTest == nil {
return nil
}
descriptionView.Clear()
fmt.Fprint(descriptionView, currentTest.Description())
return nil
}
func quit(g *gocui.Gui, v *gocui.View) error {
return gocui.ErrQuit
}
func runTuiTest(test *components.IntegrationTest, sandbox bool, waitForDebugger bool, raceDetector bool, inputDelay int) {
err := components.RunTests(components.RunTestArgs{
Tests: []*components.IntegrationTest{test},
Logf: log.Printf,
RunCmd: runCmdInTerminal,
TestWrapper: runAndPrintError,
Sandbox: sandbox,
WaitForDebugger: waitForDebugger,
RaceDetector: raceDetector,
CodeCoverageDir: "",
InputDelay: inputDelay,
MaxAttempts: 1,
})
if err != nil {
log.Println(err.Error())
}
}
func runAndPrintError(test *components.IntegrationTest, f func() error) {
if err := f(); err != nil {
log.Println(err.Error())
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/clients/cli.go | pkg/integration/clients/cli.go | package clients
import (
"log"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"github.com/jesseduffield/lazycore/pkg/utils"
"github.com/jesseduffield/lazygit/pkg/integration/components"
"github.com/jesseduffield/lazygit/pkg/integration/tests"
"github.com/samber/lo"
)
// see pkg/integration/README.md
// The purpose of this program is to run integration tests. It does this by
// building our injector program (in the sibling injector directory) and then for
// each test we're running, invoke the injector program with the test's name as
// an environment variable. Then the injector finds the test and passes it to
// the lazygit startup code.
// If invoked directly, you can specify tests to run by passing their names as positional arguments
func RunCLI(testNames []string, slow bool, sandbox bool, waitForDebugger bool, raceDetector bool) {
inputDelay := tryConvert(os.Getenv("INPUT_DELAY"), 0)
if slow {
inputDelay = SLOW_INPUT_DELAY
}
err := components.RunTests(components.RunTestArgs{
Tests: getTestsToRun(testNames),
Logf: log.Printf,
RunCmd: runCmdInTerminal,
TestWrapper: runAndPrintFatalError,
Sandbox: sandbox,
WaitForDebugger: waitForDebugger,
RaceDetector: raceDetector,
CodeCoverageDir: "",
InputDelay: inputDelay,
MaxAttempts: 1,
})
if err != nil {
log.Print(err.Error())
}
}
func runAndPrintFatalError(test *components.IntegrationTest, f func() error) {
if err := f(); err != nil {
log.Fatal(err.Error())
}
}
func getTestsToRun(testNames []string) []*components.IntegrationTest {
allIntegrationTests := tests.GetTests(utils.GetLazyRootDirectory())
var testsToRun []*components.IntegrationTest
if len(testNames) == 0 {
return allIntegrationTests
}
testNames = lo.Map(testNames, func(name string, _ int) string {
// allowing full test paths to be passed for convenience
return strings.TrimSuffix(
regexp.MustCompile(`.*pkg/integration/tests/`).ReplaceAllString(name, ""),
".go",
)
})
if lo.SomeBy(testNames, func(name string) bool {
return strings.HasSuffix(name, "/shared")
}) {
log.Fatalf("'shared' is a reserved name for tests that are shared between multiple test files. Please rename your test.")
}
outer:
for _, testName := range testNames {
// check if our given test name actually exists
for _, test := range allIntegrationTests {
if test.Name() == testName {
testsToRun = append(testsToRun, test)
continue outer
}
}
log.Fatalf("test %s not found. Perhaps you forgot to add it to `pkg/integration/integration_tests/test_list.go`? This can be done by running `go generate ./...` from the Lazygit root. You'll need to ensure that your test name and the file name match (where the test name is in PascalCase and the file name is in snake_case).", testName)
}
return testsToRun
}
func runCmdInTerminal(cmd *exec.Cmd) (int, error) {
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return -1, err
}
return cmd.Process.Pid, cmd.Wait()
}
func tryConvert(numStr string, defaultVal int) int {
num, err := strconv.Atoi(numStr)
if err != nil {
return defaultVal
}
return num
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/integration/clients/injector/main.go | pkg/integration/clients/injector/main.go | package main
import (
"fmt"
"os"
"time"
"github.com/jesseduffield/lazygit/pkg/app"
"github.com/jesseduffield/lazygit/pkg/app/daemon"
"github.com/jesseduffield/lazygit/pkg/integration/components"
"github.com/jesseduffield/lazygit/pkg/integration/tests"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
"github.com/mitchellh/go-ps"
)
// The purpose of this program is to run lazygit with an integration test passed in.
// We could have done the check on TEST_NAME in the root main.go but
// that would mean lazygit would be depending on integration test code which
// would bloat the binary.
// You should not invoke this program directly. Instead you should go through
// go run cmd/integration_test/main.go
func main() {
dummyBuildInfo := &app.BuildInfo{
Commit: "",
Date: "",
Version: "",
BuildSource: "integration test",
}
integrationTest := getIntegrationTest()
if os.Getenv(components.WAIT_FOR_DEBUGGER_ENV_VAR) != "" && !daemon.InDaemonMode() {
println("Waiting for debugger to attach...")
for !isDebuggerAttached() {
time.Sleep(time.Millisecond * 100)
}
println("Debugger attached, continuing")
}
app.Start(dummyBuildInfo, integrationTest)
}
func getIntegrationTest() integrationTypes.IntegrationTest {
if daemon.InDaemonMode() {
// if we've invoked lazygit as a daemon from within lazygit,
// we don't want to pass a test to the rest of the code.
return nil
}
integrationTestName := os.Getenv(components.TEST_NAME_ENV_VAR)
if integrationTestName == "" {
panic(fmt.Sprintf(
"expected %s environment variable to be set, given that we're running an integration test",
components.TEST_NAME_ENV_VAR,
))
}
lazygitRootDir := os.Getenv(components.LAZYGIT_ROOT_DIR)
allTests := tests.GetTests(lazygitRootDir)
for _, candidateTest := range allTests {
if candidateTest.Name() == integrationTestName {
return candidateTest
}
}
panic("Could not find integration test with name: " + integrationTestName)
}
// Returns whether we are running under a debugger. It uses a heuristic to find
// out: when using dlv, it starts a debugserver executable (which is part of
// lldb), and the debuggee becomes a child process of that. So if the name of
// our parent process is "debugserver", we run under a debugger. This works even
// if the parent process used to be the shell and you then attach to the running
// executable.
//
// On Mac this works with VS Code, with the Jetbrains Goland IDE, and when using
// dlv attach in a terminal. I have not been able to verify that it works on
// other platforms, it may have to be adapted there.
func isDebuggerAttached() bool {
process, err := ps.FindProcess(os.Getppid())
if err != nil {
return false
}
return process.Executable() == "debugserver"
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/env/env.go | pkg/env/env.go | package env
import (
"os"
)
// This package encapsulates accessing/mutating the ENV of the program.
func GetGitDirEnv() string {
return os.Getenv("GIT_DIR")
}
func SetGitDirEnv(value string) {
os.Setenv("GIT_DIR", value)
}
func GetWorkTreeEnv() string {
return os.Getenv("GIT_WORK_TREE")
}
func SetWorkTreeEnv(value string) {
os.Setenv("GIT_WORK_TREE", value)
}
func UnsetGitLocationEnvVars() {
_ = os.Unsetenv("GIT_DIR")
_ = os.Unsetenv("GIT_WORK_TREE")
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/app/entry_point.go | pkg/app/entry_point.go | package app
import (
"bytes"
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"github.com/integrii/flaggy"
"github.com/jesseduffield/lazygit/pkg/app/daemon"
appTypes "github.com/jesseduffield/lazygit/pkg/app/types"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/env"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
"github.com/jesseduffield/lazygit/pkg/logs/tail"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
"gopkg.in/yaml.v3"
)
type cliArgs struct {
RepoPath string
FilterPath string
GitArg string
UseConfigDir string
WorkTree string
GitDir string
CustomConfigFile string
ScreenMode string
PrintVersionInfo bool
Debug bool
TailLogs bool
Profile bool
PrintDefaultConfig bool
PrintConfigDir bool
}
type BuildInfo struct {
Commit string
Date string
Version string
BuildSource string
}
func Start(buildInfo *BuildInfo, integrationTest integrationTypes.IntegrationTest) {
cliArgs := parseCliArgsAndEnvVars()
mergeBuildInfo(buildInfo)
if cliArgs.RepoPath != "" {
if cliArgs.WorkTree != "" || cliArgs.GitDir != "" {
log.Fatal("--path option is incompatible with the --work-tree and --git-dir options")
}
absRepoPath, err := filepath.Abs(cliArgs.RepoPath)
if err != nil {
log.Fatal(err)
}
if isRepo, err := isDirectoryAGitRepository(absRepoPath); err != nil || !isRepo {
log.Fatal(absRepoPath + " is not a valid git repository.")
}
cliArgs.GitDir = filepath.Join(absRepoPath, ".git")
err = os.Chdir(absRepoPath)
if err != nil {
log.Fatalf("Failed to change directory to %s: %v", absRepoPath, err)
}
} else if cliArgs.WorkTree != "" {
env.SetWorkTreeEnv(cliArgs.WorkTree)
if err := os.Chdir(cliArgs.WorkTree); err != nil {
log.Fatalf("Failed to change directory to %s: %v", cliArgs.WorkTree, err)
}
}
if cliArgs.CustomConfigFile != "" {
os.Setenv("LG_CONFIG_FILE", cliArgs.CustomConfigFile)
}
if cliArgs.UseConfigDir != "" {
os.Setenv("CONFIG_DIR", cliArgs.UseConfigDir)
}
if cliArgs.GitDir != "" {
env.SetGitDirEnv(cliArgs.GitDir)
}
if cliArgs.PrintVersionInfo {
gitVersion := getGitVersionInfo()
fmt.Printf("commit=%s, build date=%s, build source=%s, version=%s, os=%s, arch=%s, git version=%s\n", buildInfo.Commit, buildInfo.Date, buildInfo.BuildSource, buildInfo.Version, runtime.GOOS, runtime.GOARCH, gitVersion)
os.Exit(0)
}
if cliArgs.PrintDefaultConfig {
var buf bytes.Buffer
encoder := yaml.NewEncoder(&buf)
err := encoder.Encode(config.GetDefaultConfig())
if err != nil {
log.Fatal(err.Error())
}
fmt.Printf("%s\n", buf.String())
os.Exit(0)
}
if cliArgs.PrintConfigDir {
fmt.Printf("%s\n", config.ConfigDir())
os.Exit(0)
}
if cliArgs.TailLogs {
logPath, err := config.LogPath()
if err != nil {
log.Fatal(err.Error())
}
tail.TailLogs(logPath)
os.Exit(0)
}
tempDirBase := getTempDirBase()
tempDir, err := os.MkdirTemp(tempDirBase, "lazygit-*")
if err != nil {
if os.IsPermission(err) {
log.Fatalf("Your temp directory (%s) is not writeable. Try if rebooting your machine fixes this.", tempDirBase)
}
log.Fatal(err.Error())
}
defer os.RemoveAll(tempDir)
appConfig, err := config.NewAppConfig("lazygit", buildInfo.Version, buildInfo.Commit, buildInfo.Date, buildInfo.BuildSource, cliArgs.Debug, tempDir)
if err != nil {
log.Fatal(err.Error())
}
if integrationTest != nil {
integrationTest.SetupConfig(appConfig)
// Set this to true so that integration tests don't have to explicitly deal with the hunk
// staging hint:
appConfig.GetAppState().DidShowHunkStagingHint = true
// Preserve the changes that the test setup just made to the config, so
// they don't get lost when we reload the config while running the test
// (which happens when switching between repos, going in and out of
// submodules, etc).
appConfig.SaveGlobalUserConfig()
}
common, err := NewCommon(appConfig)
if err != nil {
log.Fatal(err)
}
if daemon.InDaemonMode() {
daemon.Handle(common)
return
}
if cliArgs.Profile {
go func() {
if err := http.ListenAndServe("localhost:6060", nil); err != nil {
log.Fatal(err)
}
}()
}
parsedGitArg := parseGitArg(cliArgs.GitArg)
Run(appConfig, common, appTypes.NewStartArgs(cliArgs.FilterPath, parsedGitArg, cliArgs.ScreenMode, integrationTest))
}
func parseCliArgsAndEnvVars() *cliArgs {
flaggy.DefaultParser.ShowVersionWithVersionFlag = false
repoPath := ""
flaggy.String(&repoPath, "p", "path", "Path of git repo. (equivalent to --work-tree=<path> --git-dir=<path>/.git/)")
filterPath := ""
flaggy.String(&filterPath, "f", "filter", "Path to filter on in `git log -- <path>`. When in filter mode, the commits, reflog, and stash are filtered based on the given path, and some operations are restricted")
gitArg := ""
flaggy.AddPositionalValue(&gitArg, "git-arg", 1, false, "Panel to focus upon opening lazygit. Accepted values (based on git terminology): status, branch, log, stash. Ignored if --filter arg is passed.")
printVersionInfo := false
flaggy.Bool(&printVersionInfo, "v", "version", "Print the current version")
debug := false
flaggy.Bool(&debug, "d", "debug", "Run in debug mode with logging (see --logs flag below). Use the LOG_LEVEL env var to set the log level (debug/info/warn/error)")
tailLogs := false
flaggy.Bool(&tailLogs, "l", "logs", "Tail lazygit logs (intended to be used when `lazygit --debug` is called in a separate terminal tab)")
profile := false
flaggy.Bool(&profile, "", "profile", "Start the profiler and serve it on http port 6060. See CONTRIBUTING.md for more info.")
printDefaultConfig := false
flaggy.Bool(&printDefaultConfig, "c", "config", "Print the default config")
printConfigDir := false
flaggy.Bool(&printConfigDir, "cd", "print-config-dir", "Print the config directory")
useConfigDir := ""
flaggy.String(&useConfigDir, "ucd", "use-config-dir", "override default config directory with provided directory")
workTree := os.Getenv("GIT_WORK_TREE")
flaggy.String(&workTree, "w", "work-tree", "equivalent of the --work-tree git argument")
gitDir := os.Getenv("GIT_DIR")
flaggy.String(&gitDir, "g", "git-dir", "equivalent of the --git-dir git argument")
customConfigFile := ""
flaggy.String(&customConfigFile, "ucf", "use-config-file", "Comma separated list to custom config file(s)")
screenMode := ""
flaggy.String(&screenMode, "sm", "screen-mode", "The initial screen-mode, which determines the size of the focused panel. Valid options: 'normal' (default), 'half', 'full'")
flaggy.Parse()
if os.Getenv("DEBUG") == "TRUE" {
debug = true
}
return &cliArgs{
RepoPath: repoPath,
FilterPath: filterPath,
GitArg: gitArg,
PrintVersionInfo: printVersionInfo,
Debug: debug,
TailLogs: tailLogs,
Profile: profile,
PrintDefaultConfig: printDefaultConfig,
PrintConfigDir: printConfigDir,
UseConfigDir: useConfigDir,
WorkTree: workTree,
GitDir: gitDir,
CustomConfigFile: customConfigFile,
ScreenMode: screenMode,
}
}
func parseGitArg(gitArg string) appTypes.GitArg {
typedArg := appTypes.GitArg(gitArg)
// using switch so that linter catches when a new git arg value is defined but not handled here
switch typedArg {
case appTypes.GitArgNone, appTypes.GitArgStatus, appTypes.GitArgBranch, appTypes.GitArgLog, appTypes.GitArgStash:
return typedArg
}
permittedValues := []string{
string(appTypes.GitArgStatus),
string(appTypes.GitArgBranch),
string(appTypes.GitArgLog),
string(appTypes.GitArgStash),
}
log.Fatalf("Invalid git arg value: '%s'. Must be one of the following values: %s. e.g. 'lazygit status'. See 'lazygit --help'.",
gitArg,
strings.Join(permittedValues, ", "),
)
panic("unreachable")
}
// the buildInfo struct we get passed in is based on what's baked into the lazygit
// binary via the LDFLAGS argument. Some lazygit distributions will make use of these
// arguments and some will not. Go recently started baking in build info
// into the binary by default e.g. the git commit hash. So in this function
// we merge the two together, giving priority to the stuff set by LDFLAGS.
// Note: this mutates the argument passed in
func mergeBuildInfo(buildInfo *BuildInfo) {
// if the version has already been set by build flags then we'll honour that.
// chances are it's something like v0.31.0 which is more informative than a
// commit hash.
if buildInfo.Version != "" {
return
}
buildInfo.Version = "unversioned"
goBuildInfo, ok := debug.ReadBuildInfo()
if !ok {
return
}
revision, ok := lo.Find(goBuildInfo.Settings, func(setting debug.BuildSetting) bool {
return setting.Key == "vcs.revision"
})
if ok {
buildInfo.Commit = revision.Value
// if lazygit was built from source we'll show the version as the
// abbreviated commit hash
buildInfo.Version = utils.ShortHash(revision.Value)
}
// if version hasn't been set we assume that neither has the date
time, ok := lo.Find(goBuildInfo.Settings, func(setting debug.BuildSetting) bool {
return setting.Key == "vcs.time"
})
if ok {
buildInfo.Date = time.Value
}
}
func getGitVersionInfo() string {
cmd := exec.Command("git", "--version")
stdout, _ := cmd.Output()
gitVersion := strings.Trim(strings.TrimPrefix(string(stdout), "git version "), " \r\n")
return gitVersion
}
func getTempDirBase() string {
tempDir := os.TempDir()
user, err := user.Current()
if err != nil || user.Uid == "" {
return tempDir
}
tmpDirBase := filepath.Join(tempDir, "lazygit-"+user.Uid)
if err := os.MkdirAll(tmpDirBase, 0o700); err != nil {
return tempDir
}
return tmpDirBase
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/app/errors.go | pkg/app/errors.go | package app
import (
"strings"
"github.com/jesseduffield/lazygit/pkg/i18n"
"github.com/samber/lo"
)
type errorMapping struct {
originalError string
newError string
}
// knownError takes an error and tells us whether it's an error that we know about where we can print a nicely formatted version of it rather than panicking with a stack trace
func knownError(tr *i18n.TranslationSet, err error) (string, bool) {
errorMessage := err.Error()
knownErrorMessages := []string{minGitVersionErrorMessage(tr)}
if lo.Contains(knownErrorMessages, errorMessage) {
return errorMessage, true
}
mappings := []errorMapping{
{
originalError: "fatal: not a git repository",
newError: tr.NotARepository,
},
{
originalError: "getwd: no such file or directory",
newError: tr.WorkingDirectoryDoesNotExist,
},
}
if mapping, ok := lo.Find(mappings, func(mapping errorMapping) bool {
return strings.Contains(errorMessage, mapping.originalError)
}); ok {
return mapping.newError, true
}
return "", false
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/app/app.go | pkg/app/app.go | package app
import (
"bufio"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"github.com/go-errors/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
appTypes "github.com/jesseduffield/lazygit/pkg/app/types"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/constants"
"github.com/jesseduffield/lazygit/pkg/env"
"github.com/jesseduffield/lazygit/pkg/gui"
"github.com/jesseduffield/lazygit/pkg/i18n"
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
"github.com/jesseduffield/lazygit/pkg/logs"
"github.com/jesseduffield/lazygit/pkg/updates"
)
// App is the struct that's instantiated from within main.go and it manages
// bootstrapping and running the application.
type App struct {
*common.Common
closers []io.Closer
Config config.AppConfigurer
OSCommand *oscommands.OSCommand
Gui *gui.Gui
}
func Run(
config config.AppConfigurer,
common *common.Common,
startArgs appTypes.StartArgs,
) {
app, err := NewApp(config, startArgs.IntegrationTest, common)
if err == nil {
err = app.Run(startArgs)
}
if err != nil {
if errorMessage, known := knownError(common.Tr, err); known {
log.Fatal(errorMessage)
}
newErr := errors.Wrap(err, 0)
stackTrace := newErr.ErrorStack()
app.Log.Error(stackTrace)
log.Fatalf("%s: %s\n\n%s", common.Tr.ErrorOccurred, constants.Links.Issues, stackTrace)
}
}
func NewCommon(config config.AppConfigurer) (*common.Common, error) {
userConfig := config.GetUserConfig()
appState := config.GetAppState()
log := newLogger(config)
// Initialize with English for the time being; the real translation set for
// the configured language will be read after reading the user config
tr := i18n.EnglishTranslationSet()
cmn := &common.Common{
Log: log,
Tr: tr,
AppState: appState,
Debug: config.GetDebug(),
Fs: afero.NewOsFs(),
}
cmn.SetUserConfig(userConfig)
return cmn, nil
}
func newLogger(cfg config.AppConfigurer) *logrus.Entry {
if cfg.GetDebug() {
logPath, err := config.LogPath()
if err != nil {
log.Fatal(err)
}
return logs.NewDevelopmentLogger(logPath)
}
return logs.NewProductionLogger()
}
// NewApp bootstrap a new application
func NewApp(config config.AppConfigurer, test integrationTypes.IntegrationTest, common *common.Common) (*App, error) {
app := &App{
closers: []io.Closer{},
Config: config,
Common: common,
}
app.OSCommand = oscommands.NewOSCommand(common, config, oscommands.GetPlatform(), oscommands.NewNullGuiIO(app.Log))
updater, err := updates.NewUpdater(common, config, app.OSCommand)
if err != nil {
return app, err
}
dirName, err := os.Getwd()
if err != nil {
return app, err
}
gitVersion, err := app.validateGitVersion()
if err != nil {
return app, err
}
// If we're not in a repo, GetRepoPaths will return an error. The error is moot for us
// at this stage, since we'll try to init a new repo in setupRepo(), below
repoPaths, err := git_commands.GetRepoPaths(app.OSCommand.Cmd, gitVersion)
if err != nil {
common.Log.Infof("Error getting repo paths: %v", err)
}
showRecentRepos, err := app.setupRepo(repoPaths)
if err != nil {
return app, err
}
// used for testing purposes
if os.Getenv("SHOW_RECENT_REPOS") == "true" {
showRecentRepos = true
}
app.Gui, err = gui.NewGui(common, config, gitVersion, updater, showRecentRepos, dirName, test)
if err != nil {
return app, err
}
return app, nil
}
const minGitVersionStr = "2.32.0"
func minGitVersionErrorMessage(tr *i18n.TranslationSet) string {
return fmt.Sprintf(tr.MinGitVersionError, minGitVersionStr)
}
func (app *App) validateGitVersion() (*git_commands.GitVersion, error) {
version, err := git_commands.GetGitVersion(app.OSCommand)
// if we get an error anywhere here we'll show the same status
minVersionError := errors.New(minGitVersionErrorMessage(app.Tr))
if err != nil {
return nil, minVersionError
}
minRequiredVersion, _ := git_commands.ParseGitVersion(minGitVersionStr)
if version.IsOlderThanVersion(minRequiredVersion) {
return nil, minVersionError
}
return version, nil
}
func isDirectoryAGitRepository(dir string) (bool, error) {
info, err := os.Stat(filepath.Join(dir, ".git"))
return info != nil, err
}
func openRecentRepo(app *App) bool {
for _, repoDir := range app.Config.GetAppState().RecentRepos {
if isRepo, _ := isDirectoryAGitRepository(repoDir); isRepo {
if err := os.Chdir(repoDir); err == nil {
return true
}
}
}
return false
}
func (app *App) setupRepo(
repoPaths *git_commands.RepoPaths,
) (bool, error) {
if env.GetGitDirEnv() != "" {
// we've been given the git dir directly. Skip setup
return false, nil
}
// if we are not in a git repo, we ask if we want to `git init`
if repoPaths == nil {
cwd, err := os.Getwd()
if err != nil {
return false, err
}
if isRepo, err := isDirectoryAGitRepository(cwd); isRepo {
return false, err
}
var shouldInitRepo bool
initialBranchArg := ""
switch app.UserConfig().NotARepository {
case "prompt":
// Offer to initialize a new repository in current directory.
fmt.Print(app.Tr.CreateRepo)
response, _ := bufio.NewReader(os.Stdin).ReadString('\n')
shouldInitRepo = (strings.Trim(response, " \r\n") == "y")
if shouldInitRepo {
// Ask for the initial branch name
fmt.Print(app.Tr.InitialBranch)
response, _ := bufio.NewReader(os.Stdin).ReadString('\n')
if trimmedResponse := strings.Trim(response, " \r\n"); len(trimmedResponse) > 0 {
initialBranchArg += "--initial-branch=" + trimmedResponse
}
}
case "create":
shouldInitRepo = true
case "skip":
shouldInitRepo = false
case "quit":
fmt.Fprintln(os.Stderr, app.Tr.NotARepository)
os.Exit(1)
default:
fmt.Fprintln(os.Stderr, app.Tr.IncorrectNotARepository)
os.Exit(1)
}
if shouldInitRepo {
args := []string{"git", "init"}
if initialBranchArg != "" {
args = append(args, initialBranchArg)
}
if err := app.OSCommand.Cmd.New(args).Run(); err != nil {
return false, err
}
return false, nil
}
// check if we have a recent repo we can open
for _, repoDir := range app.Config.GetAppState().RecentRepos {
if isRepo, _ := isDirectoryAGitRepository(repoDir); isRepo {
if err := os.Chdir(repoDir); err == nil {
return true, nil
}
}
}
fmt.Fprintln(os.Stderr, app.Tr.NoRecentRepositories)
os.Exit(1)
}
// Run this afterward so that the previous repo creation steps can run without this interfering
if repoPaths.IsBareRepo() {
fmt.Print(app.Tr.BareRepo)
response, _ := bufio.NewReader(os.Stdin).ReadString('\n')
if shouldOpenRecent := strings.Trim(response, " \r\n") == "y"; !shouldOpenRecent {
os.Exit(0)
}
if didOpenRepo := openRecentRepo(app); didOpenRepo {
return true, nil
}
fmt.Println(app.Tr.NoRecentRepositories)
os.Exit(1)
}
return false, nil
}
func (app *App) Run(startArgs appTypes.StartArgs) error {
err := app.Gui.RunAndHandleError(startArgs)
return err
}
// Close closes any resources
func (app *App) Close() error {
for _, closer := range app.closers {
if err := closer.Close(); err != nil {
return err
}
}
return nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/app/types/types.go | pkg/app/types/types.go | package app
import (
integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
)
// StartArgs is the struct that represents some things we want to do on program start
type StartArgs struct {
// GitArg determines what context we open in
GitArg GitArg
// integration test (only relevant when invoking lazygit in the context of an integration test)
IntegrationTest integrationTypes.IntegrationTest
// FilterPath determines which path we're going to filter on so that we only see commits from that file.
FilterPath string
// ScreenMode determines the initial Screen Mode (normal, half or full) to use
ScreenMode string
}
type GitArg string
const (
GitArgNone GitArg = ""
GitArgStatus GitArg = "status"
GitArgBranch GitArg = "branch"
GitArgLog GitArg = "log"
GitArgStash GitArg = "stash"
)
func NewStartArgs(filterPath string, gitArg GitArg, screenMode string, test integrationTypes.IntegrationTest) StartArgs {
return StartArgs{
FilterPath: filterPath,
GitArg: gitArg,
ScreenMode: screenMode,
IntegrationTest: test,
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/app/daemon/daemon.go | pkg/app/daemon/daemon.go | package daemon
import (
"encoding/json"
"fmt"
"log"
"os"
"os/exec"
"strconv"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/samber/lo"
)
// Sometimes lazygit will be invoked in daemon mode from a parent lazygit process.
// We do this when git lets us supply a program to run within a git command.
// For example, if we want to ensure that a git command doesn't hang due to
// waiting for an editor to save a commit message, we can tell git to invoke lazygit
// as the editor via 'GIT_EDITOR=lazygit', and use the env var
// 'LAZYGIT_DAEMON_KIND=1' (exit immediately) to specify that we want to run lazygit
// as a daemon which simply exits immediately.
//
// 'Daemon' is not the best name for this, because it's not a persistent background
// process, but it's close enough.
type DaemonKind int
const (
// for when we fail to parse the daemon kind
DaemonKindUnknown DaemonKind = iota
DaemonKindExitImmediately
DaemonKindRemoveUpdateRefsForCopiedBranch
DaemonKindMoveTodosUp
DaemonKindMoveTodosDown
DaemonKindInsertBreak
DaemonKindChangeTodoActions
DaemonKindDropMergeCommit
DaemonKindMoveFixupCommitDown
DaemonKindWriteRebaseTodo
)
const (
DaemonKindEnvKey string = "LAZYGIT_DAEMON_KIND"
// Contains json-encoded arguments to the daemon
DaemonInstructionEnvKey string = "LAZYGIT_DAEMON_INSTRUCTION"
)
func getInstruction() Instruction {
jsonData := os.Getenv(DaemonInstructionEnvKey)
mapping := map[DaemonKind]func(string) Instruction{
DaemonKindExitImmediately: deserializeInstruction[*ExitImmediatelyInstruction],
DaemonKindRemoveUpdateRefsForCopiedBranch: deserializeInstruction[*RemoveUpdateRefsForCopiedBranchInstruction],
DaemonKindChangeTodoActions: deserializeInstruction[*ChangeTodoActionsInstruction],
DaemonKindDropMergeCommit: deserializeInstruction[*DropMergeCommitInstruction],
DaemonKindMoveFixupCommitDown: deserializeInstruction[*MoveFixupCommitDownInstruction],
DaemonKindMoveTodosUp: deserializeInstruction[*MoveTodosUpInstruction],
DaemonKindMoveTodosDown: deserializeInstruction[*MoveTodosDownInstruction],
DaemonKindInsertBreak: deserializeInstruction[*InsertBreakInstruction],
DaemonKindWriteRebaseTodo: deserializeInstruction[*WriteRebaseTodoInstruction],
}
return mapping[getDaemonKind()](jsonData)
}
func Handle(common *common.Common) {
if !InDaemonMode() {
return
}
instruction := getInstruction()
if err := instruction.run(common); err != nil {
log.Fatal(err)
}
}
func InDaemonMode() bool {
return getDaemonKind() != DaemonKindUnknown
}
func getDaemonKind() DaemonKind {
intValue, err := strconv.Atoi(os.Getenv(DaemonKindEnvKey))
if err != nil {
return DaemonKindUnknown
}
return DaemonKind(intValue)
}
func getCommentChar() byte {
cmd := exec.Command("git", "config", "--get", "--null", "core.commentChar")
if output, err := cmd.Output(); err == nil && len(output) == 2 {
return output[0]
}
return '#'
}
// An Instruction is a command to be run by lazygit in daemon mode.
// It is serialized to json and passed to lazygit via environment variables
type Instruction interface {
Kind() DaemonKind
SerializedInstructions() string
// runs the instruction
run(common *common.Common) error
}
func serializeInstruction[T any](instruction T) string {
jsonData, err := json.Marshal(instruction)
if err != nil {
// this should never happen
panic(err)
}
return string(jsonData)
}
func deserializeInstruction[T Instruction](jsonData string) Instruction {
var instruction T
err := json.Unmarshal([]byte(jsonData), &instruction)
if err != nil {
panic(err)
}
return instruction
}
func ToEnvVars(instruction Instruction) []string {
return []string{
fmt.Sprintf("%s=%d", DaemonKindEnvKey, instruction.Kind()),
fmt.Sprintf("%s=%s", DaemonInstructionEnvKey, instruction.SerializedInstructions()),
}
}
type ExitImmediatelyInstruction struct{}
func (self *ExitImmediatelyInstruction) Kind() DaemonKind {
return DaemonKindExitImmediately
}
func (self *ExitImmediatelyInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *ExitImmediatelyInstruction) run(common *common.Common) error {
return nil
}
func NewExitImmediatelyInstruction() Instruction {
return &ExitImmediatelyInstruction{}
}
type RemoveUpdateRefsForCopiedBranchInstruction struct{}
func (self *RemoveUpdateRefsForCopiedBranchInstruction) Kind() DaemonKind {
return DaemonKindRemoveUpdateRefsForCopiedBranch
}
func (self *RemoveUpdateRefsForCopiedBranchInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *RemoveUpdateRefsForCopiedBranchInstruction) run(common *common.Common) error {
return handleInteractiveRebase(common, func(path string) error {
return nil
})
}
func NewRemoveUpdateRefsForCopiedBranchInstruction() Instruction {
return &RemoveUpdateRefsForCopiedBranchInstruction{}
}
type ChangeTodoActionsInstruction struct {
Changes []ChangeTodoAction
}
func NewChangeTodoActionsInstruction(changes []ChangeTodoAction) Instruction {
return &ChangeTodoActionsInstruction{
Changes: changes,
}
}
func (self *ChangeTodoActionsInstruction) Kind() DaemonKind {
return DaemonKindChangeTodoActions
}
func (self *ChangeTodoActionsInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *ChangeTodoActionsInstruction) run(common *common.Common) error {
return handleInteractiveRebase(common, func(path string) error {
changes := lo.Map(self.Changes, func(c ChangeTodoAction, _ int) utils.TodoChange {
return utils.TodoChange{
Hash: c.Hash,
NewAction: c.NewAction,
}
})
return utils.EditRebaseTodo(path, changes, getCommentChar())
})
}
type DropMergeCommitInstruction struct {
Hash string
}
func NewDropMergeCommitInstruction(hash string) Instruction {
return &DropMergeCommitInstruction{
Hash: hash,
}
}
func (self *DropMergeCommitInstruction) Kind() DaemonKind {
return DaemonKindDropMergeCommit
}
func (self *DropMergeCommitInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *DropMergeCommitInstruction) run(common *common.Common) error {
return handleInteractiveRebase(common, func(path string) error {
return utils.DropMergeCommit(path, self.Hash, getCommentChar())
})
}
// Takes the hash of some commit, and the hash of a fixup commit that was created
// at the end of the branch, then moves the fixup commit down to right after the
// original commit, changing its type to "fixup" (only if ChangeToFixup is true)
type MoveFixupCommitDownInstruction struct {
OriginalHash string
FixupHash string
ChangeToFixup bool
}
func NewMoveFixupCommitDownInstruction(originalHash string, fixupHash string, changeToFixup bool) Instruction {
return &MoveFixupCommitDownInstruction{
OriginalHash: originalHash,
FixupHash: fixupHash,
ChangeToFixup: changeToFixup,
}
}
func (self *MoveFixupCommitDownInstruction) Kind() DaemonKind {
return DaemonKindMoveFixupCommitDown
}
func (self *MoveFixupCommitDownInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *MoveFixupCommitDownInstruction) run(common *common.Common) error {
return handleInteractiveRebase(common, func(path string) error {
return utils.MoveFixupCommitDown(path, self.OriginalHash, self.FixupHash, self.ChangeToFixup, getCommentChar())
})
}
type MoveTodosUpInstruction struct {
Hashes []string
}
func NewMoveTodosUpInstruction(hashes []string) Instruction {
return &MoveTodosUpInstruction{
Hashes: hashes,
}
}
func (self *MoveTodosUpInstruction) Kind() DaemonKind {
return DaemonKindMoveTodosUp
}
func (self *MoveTodosUpInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *MoveTodosUpInstruction) run(common *common.Common) error {
todosToMove := lo.Map(self.Hashes, func(hash string, _ int) utils.Todo {
return utils.Todo{
Hash: hash,
}
})
return handleInteractiveRebase(common, func(path string) error {
return utils.MoveTodosUp(path, todosToMove, false, getCommentChar())
})
}
type MoveTodosDownInstruction struct {
Hashes []string
}
func NewMoveTodosDownInstruction(hashes []string) Instruction {
return &MoveTodosDownInstruction{
Hashes: hashes,
}
}
func (self *MoveTodosDownInstruction) Kind() DaemonKind {
return DaemonKindMoveTodosDown
}
func (self *MoveTodosDownInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *MoveTodosDownInstruction) run(common *common.Common) error {
todosToMove := lo.Map(self.Hashes, func(hash string, _ int) utils.Todo {
return utils.Todo{
Hash: hash,
}
})
return handleInteractiveRebase(common, func(path string) error {
return utils.MoveTodosDown(path, todosToMove, false, getCommentChar())
})
}
type InsertBreakInstruction struct{}
func NewInsertBreakInstruction() Instruction {
return &InsertBreakInstruction{}
}
func (self *InsertBreakInstruction) Kind() DaemonKind {
return DaemonKindInsertBreak
}
func (self *InsertBreakInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *InsertBreakInstruction) run(common *common.Common) error {
return handleInteractiveRebase(common, func(path string) error {
return utils.PrependStrToTodoFile(path, []byte("break\n"))
})
}
type WriteRebaseTodoInstruction struct {
TodosFileContent []byte
}
func NewWriteRebaseTodoInstruction(todosFileContent []byte) Instruction {
return &WriteRebaseTodoInstruction{
TodosFileContent: todosFileContent,
}
}
func (self *WriteRebaseTodoInstruction) Kind() DaemonKind {
return DaemonKindWriteRebaseTodo
}
func (self *WriteRebaseTodoInstruction) SerializedInstructions() string {
return serializeInstruction(self)
}
func (self *WriteRebaseTodoInstruction) run(common *common.Common) error {
return handleInteractiveRebase(common, func(path string) error {
return os.WriteFile(path, self.TodosFileContent, 0o644)
})
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/app/daemon/rebase.go | pkg/app/daemon/rebase.go | package daemon
import (
"os"
"path/filepath"
"strings"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/env"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/stefanhaller/git-todo-parser/todo"
)
type ChangeTodoAction struct {
Hash string
NewAction todo.TodoCommand
}
func handleInteractiveRebase(common *common.Common, f func(path string) error) error {
common.Log.Info("Lazygit invoked as interactive rebase demon")
common.Log.Info("args: ", os.Args)
path := os.Args[1]
if strings.HasSuffix(path, "git-rebase-todo") {
err := utils.RemoveUpdateRefsForCopiedBranch(path, getCommentChar())
if err != nil {
return err
}
return f(path)
} else if strings.HasSuffix(path, filepath.Join(gitDir(), "COMMIT_EDITMSG")) { // TODO: test
// if we are rebasing and squashing, we'll see a COMMIT_EDITMSG
// but in this case we don't need to edit it, so we'll just return
} else {
common.Log.Info("Lazygit demon did not match on any use cases")
}
return nil
}
func gitDir() string {
dir := env.GetGitDirEnv()
if dir == "" {
return ".git"
}
return dir
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/fakes/log.go | pkg/fakes/log.go | package fakes
import (
"fmt"
"testing"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
var _ logrus.FieldLogger = &FakeFieldLogger{}
// for now we're just tracking calls to the Error and Errorf methods
type FakeFieldLogger struct {
loggedErrors []string
*logrus.Entry
}
func (self *FakeFieldLogger) Error(args ...any) {
if len(args) != 1 {
panic("Expected exactly one argument to FakeFieldLogger.Error")
}
switch arg := args[0].(type) {
case error:
self.loggedErrors = append(self.loggedErrors, arg.Error())
case string:
self.loggedErrors = append(self.loggedErrors, arg)
}
}
func (self *FakeFieldLogger) Errorf(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
self.loggedErrors = append(self.loggedErrors, msg)
}
func (self *FakeFieldLogger) AssertErrors(t *testing.T, expectedErrors []string) {
t.Helper()
assert.EqualValues(t, expectedErrors, self.loggedErrors)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/commands/git.go | pkg/commands/git.go | package commands
import (
"os"
"strings"
"github.com/go-errors/errors"
gogit "github.com/jesseduffield/go-git/v5"
"github.com/jesseduffield/lazygit/pkg/commands/git_commands"
"github.com/jesseduffield/lazygit/pkg/commands/git_config"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/jesseduffield/lazygit/pkg/commands/patch"
"github.com/jesseduffield/lazygit/pkg/common"
"github.com/jesseduffield/lazygit/pkg/config"
"github.com/jesseduffield/lazygit/pkg/utils"
)
// GitCommand is our main git interface
type GitCommand struct {
Blame *git_commands.BlameCommands
Branch *git_commands.BranchCommands
Commit *git_commands.CommitCommands
Config *git_commands.ConfigCommands
Custom *git_commands.CustomCommands
Diff *git_commands.DiffCommands
File *git_commands.FileCommands
Flow *git_commands.FlowCommands
Patch *git_commands.PatchCommands
Rebase *git_commands.RebaseCommands
Remote *git_commands.RemoteCommands
Stash *git_commands.StashCommands
Status *git_commands.StatusCommands
Submodule *git_commands.SubmoduleCommands
Sync *git_commands.SyncCommands
Tag *git_commands.TagCommands
WorkingTree *git_commands.WorkingTreeCommands
Bisect *git_commands.BisectCommands
Worktree *git_commands.WorktreeCommands
Version *git_commands.GitVersion
RepoPaths *git_commands.RepoPaths
Loaders Loaders
}
type Loaders struct {
BranchLoader *git_commands.BranchLoader
CommitFileLoader *git_commands.CommitFileLoader
CommitLoader *git_commands.CommitLoader
FileLoader *git_commands.FileLoader
ReflogCommitLoader *git_commands.ReflogCommitLoader
RemoteLoader *git_commands.RemoteLoader
StashLoader *git_commands.StashLoader
TagLoader *git_commands.TagLoader
Worktrees *git_commands.WorktreeLoader
}
func NewGitCommand(
cmn *common.Common,
version *git_commands.GitVersion,
osCommand *oscommands.OSCommand,
gitConfig git_config.IGitConfig,
pagerConfig *config.PagerConfig,
) (*GitCommand, error) {
repoPaths, err := git_commands.GetRepoPaths(osCommand.Cmd, version)
if err != nil {
return nil, errors.Errorf("Error getting repo paths: %v", err)
}
err = os.Chdir(repoPaths.WorktreePath())
if err != nil {
return nil, utils.WrapError(err)
}
repository, err := gogit.PlainOpenWithOptions(
repoPaths.WorktreeGitDirPath(),
&gogit.PlainOpenOptions{DetectDotGit: false, EnableDotGitCommonDir: true},
)
if err != nil {
if strings.Contains(err.Error(), `unquoted '\' must be followed by new line`) {
return nil, errors.New(cmn.Tr.GitconfigParseErr)
}
return nil, err
}
return NewGitCommandAux(
cmn,
version,
osCommand,
gitConfig,
repoPaths,
repository,
pagerConfig,
), nil
}
func NewGitCommandAux(
cmn *common.Common,
version *git_commands.GitVersion,
osCommand *oscommands.OSCommand,
gitConfig git_config.IGitConfig,
repoPaths *git_commands.RepoPaths,
repo *gogit.Repository,
pagerConfig *config.PagerConfig,
) *GitCommand {
cmd := NewGitCmdObjBuilder(cmn.Log, osCommand.Cmd)
// here we're doing a bunch of dependency injection for each of our commands structs.
// This is admittedly messy, but allows us to test each command struct in isolation,
// and allows for better namespacing when compared to having every method living
// on the one struct.
// common ones are: cmn, osCommand, dotGitDir, configCommands
configCommands := git_commands.NewConfigCommands(cmn, gitConfig, repo)
gitCommon := git_commands.NewGitCommon(cmn, version, cmd, osCommand, repoPaths, repo, configCommands, pagerConfig)
fileLoader := git_commands.NewFileLoader(gitCommon, cmd, configCommands)
statusCommands := git_commands.NewStatusCommands(gitCommon)
flowCommands := git_commands.NewFlowCommands(gitCommon)
remoteCommands := git_commands.NewRemoteCommands(gitCommon)
branchCommands := git_commands.NewBranchCommands(gitCommon)
syncCommands := git_commands.NewSyncCommands(gitCommon)
tagCommands := git_commands.NewTagCommands(gitCommon)
commitCommands := git_commands.NewCommitCommands(gitCommon)
customCommands := git_commands.NewCustomCommands(gitCommon)
diffCommands := git_commands.NewDiffCommands(gitCommon)
fileCommands := git_commands.NewFileCommands(gitCommon)
submoduleCommands := git_commands.NewSubmoduleCommands(gitCommon)
workingTreeCommands := git_commands.NewWorkingTreeCommands(gitCommon, submoduleCommands, fileLoader)
rebaseCommands := git_commands.NewRebaseCommands(gitCommon, commitCommands, workingTreeCommands)
stashCommands := git_commands.NewStashCommands(gitCommon, fileLoader, workingTreeCommands)
patchBuilder := patch.NewPatchBuilder(cmn.Log,
func(from string, to string, reverse bool, filename string, plain bool) (string, error) {
return workingTreeCommands.ShowFileDiff(from, to, reverse, filename, plain)
})
patchCommands := git_commands.NewPatchCommands(gitCommon, rebaseCommands, commitCommands, statusCommands, stashCommands, patchBuilder)
bisectCommands := git_commands.NewBisectCommands(gitCommon)
worktreeCommands := git_commands.NewWorktreeCommands(gitCommon)
blameCommands := git_commands.NewBlameCommands(gitCommon)
branchLoader := git_commands.NewBranchLoader(cmn, gitCommon, cmd, branchCommands.CurrentBranchInfo, configCommands)
commitFileLoader := git_commands.NewCommitFileLoader(cmn, cmd)
commitLoader := git_commands.NewCommitLoader(cmn, cmd, statusCommands.WorkingTreeState, gitCommon)
reflogCommitLoader := git_commands.NewReflogCommitLoader(cmn, cmd)
remoteLoader := git_commands.NewRemoteLoader(cmn, cmd, repo.Remotes)
worktreeLoader := git_commands.NewWorktreeLoader(gitCommon)
stashLoader := git_commands.NewStashLoader(cmn, cmd)
tagLoader := git_commands.NewTagLoader(cmn, cmd)
return &GitCommand{
Blame: blameCommands,
Branch: branchCommands,
Commit: commitCommands,
Config: configCommands,
Custom: customCommands,
Diff: diffCommands,
File: fileCommands,
Flow: flowCommands,
Patch: patchCommands,
Rebase: rebaseCommands,
Remote: remoteCommands,
Stash: stashCommands,
Status: statusCommands,
Submodule: submoduleCommands,
Sync: syncCommands,
Tag: tagCommands,
Bisect: bisectCommands,
WorkingTree: workingTreeCommands,
Worktree: worktreeCommands,
Version: version,
Loaders: Loaders{
BranchLoader: branchLoader,
CommitFileLoader: commitFileLoader,
CommitLoader: commitLoader,
FileLoader: fileLoader,
ReflogCommitLoader: reflogCommitLoader,
RemoteLoader: remoteLoader,
Worktrees: worktreeLoader,
StashLoader: stashLoader,
TagLoader: tagLoader,
},
RepoPaths: repoPaths,
}
}
func VerifyInGitRepo(osCommand *oscommands.OSCommand) error {
return osCommand.Cmd.New(git_commands.NewGitCmd("rev-parse").Arg("--git-dir").ToArgv()).DontLog().Run()
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/commands/git_cmd_obj_builder.go | pkg/commands/git_cmd_obj_builder.go | package commands
import (
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/sirupsen/logrus"
)
// all we're doing here is wrapping the default command object builder with
// some git-specific stuff: e.g. adding a git-specific env var
type gitCmdObjBuilder struct {
innerBuilder *oscommands.CmdObjBuilder
}
var _ oscommands.ICmdObjBuilder = &gitCmdObjBuilder{}
func NewGitCmdObjBuilder(log *logrus.Entry, innerBuilder *oscommands.CmdObjBuilder) *gitCmdObjBuilder {
// the price of having a convenient interface where we can say .New(...).Run() is that our builder now depends on our runner, so when we want to wrap the default builder/runner in new functionality we need to jump through some hoops. We could avoid the use of a decorator function here by just exporting the runner field on the default builder but that would be misleading because we don't want anybody using that to run commands (i.e. we want there to be a single API used across the codebase)
updatedBuilder := innerBuilder.CloneWithNewRunner(func(runner oscommands.ICmdObjRunner) oscommands.ICmdObjRunner {
return &gitCmdObjRunner{
log: log,
innerRunner: runner,
}
})
return &gitCmdObjBuilder{
innerBuilder: updatedBuilder,
}
}
var defaultEnvVar = "GIT_OPTIONAL_LOCKS=0"
func (self *gitCmdObjBuilder) New(args []string) *oscommands.CmdObj {
return self.innerBuilder.New(args).AddEnvVars(defaultEnvVar)
}
func (self *gitCmdObjBuilder) NewShell(cmdStr string, shellFunctionsFile string) *oscommands.CmdObj {
return self.innerBuilder.NewShell(cmdStr, shellFunctionsFile).AddEnvVars(defaultEnvVar)
}
func (self *gitCmdObjBuilder) Quote(str string) string {
return self.innerBuilder.Quote(str)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/commands/git_cmd_obj_runner.go | pkg/commands/git_cmd_obj_runner.go | package commands
import (
"strings"
"time"
"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
"github.com/sirupsen/logrus"
)
// here we're wrapping the default command runner in some git-specific stuff e.g. retry logic if we get an error due to the presence of .git/index.lock
const (
WaitTime = 50 * time.Millisecond
RetryCount = 5
)
type gitCmdObjRunner struct {
log *logrus.Entry
innerRunner oscommands.ICmdObjRunner
}
func (self *gitCmdObjRunner) Run(cmdObj *oscommands.CmdObj) error {
_, err := self.RunWithOutput(cmdObj)
return err
}
func (self *gitCmdObjRunner) RunWithOutput(cmdObj *oscommands.CmdObj) (string, error) {
var output string
var err error
for range RetryCount {
newCmdObj := cmdObj.Clone()
output, err = self.innerRunner.RunWithOutput(newCmdObj)
if err == nil || !strings.Contains(output, ".git/index.lock") {
return output, err
}
// if we have an error based on the index lock, we should wait a bit and then retry
self.log.Warn("index.lock prevented command from running. Retrying command after a small wait")
time.Sleep(WaitTime)
}
return output, err
}
func (self *gitCmdObjRunner) RunWithOutputs(cmdObj *oscommands.CmdObj) (string, string, error) {
var stdout, stderr string
var err error
for range RetryCount {
newCmdObj := cmdObj.Clone()
stdout, stderr, err = self.innerRunner.RunWithOutputs(newCmdObj)
if err == nil || !strings.Contains(stdout+stderr, ".git/index.lock") {
return stdout, stderr, err
}
// if we have an error based on the index lock, we should wait a bit and then retry
self.log.Warn("index.lock prevented command from running. Retrying command after a small wait")
time.Sleep(WaitTime)
}
return stdout, stderr, err
}
// Retry logic not implemented here, but these commands typically don't need to obtain a lock.
func (self *gitCmdObjRunner) RunAndProcessLines(cmdObj *oscommands.CmdObj, onLine func(line string) (bool, error)) error {
return self.innerRunner.RunAndProcessLines(cmdObj, onLine)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/commands/oscommands/gui_io.go | pkg/commands/oscommands/gui_io.go | package oscommands
import (
"io"
"github.com/sirupsen/logrus"
)
// this struct captures some IO stuff
type guiIO struct {
// this is for logging anything we want. It'll be written to a log file for the sake
// of debugging.
log *logrus.Entry
// this is for us to log the command we're about to run e.g. 'git push'. The GUI
// will write this to a log panel so that the user can see which commands are being
// run.
// The isCommandLineCommand arg is there so that we can style the log differently
// depending on whether we're directly outputting a command we're about to run that
// will be run on the command line, or if we're using something from Go's standard lib.
logCommandFn func(str string, isCommandLineCommand bool)
// this is for us to directly write the output of a command. We will do this for
// certain commands like 'git push'. The GUI will write this to a command output panel.
// We need a new cmd writer per command, hence it being a function.
newCmdWriterFn func() io.Writer
// this allows us to request info from the user like username/password, in the event
// that a command requests it.
// the 'credential' arg is something like 'username' or 'password'
promptForCredentialFn func(credential CredentialType) <-chan string
}
func NewGuiIO(
log *logrus.Entry,
logCommandFn func(string, bool),
newCmdWriterFn func() io.Writer,
promptForCredentialFn func(CredentialType) <-chan string,
) *guiIO {
return &guiIO{
log: log,
logCommandFn: logCommandFn,
newCmdWriterFn: newCmdWriterFn,
promptForCredentialFn: promptForCredentialFn,
}
}
// we use this function when we want to access the functionality of our OS struct but we
// don't have anywhere to log things, or request input from the user.
func NewNullGuiIO(log *logrus.Entry) *guiIO {
return &guiIO{
log: log,
logCommandFn: func(string, bool) {},
newCmdWriterFn: func() io.Writer { return io.Discard },
promptForCredentialFn: failPromptFn,
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/commands/oscommands/fake_cmd_obj_runner.go | pkg/commands/oscommands/fake_cmd_obj_runner.go | package oscommands
import (
"bufio"
"fmt"
"strings"
"sync"
"testing"
"github.com/go-errors/errors"
"github.com/samber/lo"
"golang.org/x/exp/slices"
)
// for use in testing
type FakeCmdObjRunner struct {
t *testing.T
// commands can be run in any order; mimicking the concurrent behaviour of
// production code.
expectedCmds []CmdObjMatcher
invokedCmdIndexes []int
mutex sync.Mutex
}
type CmdObjMatcher struct {
description string
// returns true if the matcher matches the command object
test func(*CmdObj) bool
// output of the command
output string
// error of the command
err error
}
var _ ICmdObjRunner = &FakeCmdObjRunner{}
func NewFakeRunner(t *testing.T) *FakeCmdObjRunner { //nolint:thelper
return &FakeCmdObjRunner{t: t}
}
func (self *FakeCmdObjRunner) remainingExpectedCmds() []CmdObjMatcher {
return lo.Filter(self.expectedCmds, func(_ CmdObjMatcher, i int) bool {
return !lo.Contains(self.invokedCmdIndexes, i)
})
}
func (self *FakeCmdObjRunner) Run(cmdObj *CmdObj) error {
_, err := self.RunWithOutput(cmdObj)
return err
}
func (self *FakeCmdObjRunner) RunWithOutput(cmdObj *CmdObj) (string, error) {
self.mutex.Lock()
defer self.mutex.Unlock()
if len(self.remainingExpectedCmds()) == 0 {
self.t.Errorf("ran too many commands. Unexpected command: `%s`", cmdObj.ToString())
return "", errors.New("ran too many commands")
}
for i := range self.expectedCmds {
if lo.Contains(self.invokedCmdIndexes, i) {
continue
}
expectedCmd := self.expectedCmds[i]
matched := expectedCmd.test(cmdObj)
if matched {
self.invokedCmdIndexes = append(self.invokedCmdIndexes, i)
return expectedCmd.output, expectedCmd.err
}
}
self.t.Errorf("Unexpected command: `%s`", cmdObj.ToString())
return "", nil
}
func (self *FakeCmdObjRunner) RunWithOutputs(cmdObj *CmdObj) (string, string, error) {
output, err := self.RunWithOutput(cmdObj)
return output, "", err
}
func (self *FakeCmdObjRunner) RunAndProcessLines(cmdObj *CmdObj, onLine func(line string) (bool, error)) error {
output, err := self.RunWithOutput(cmdObj)
if err != nil {
return err
}
scanner := bufio.NewScanner(strings.NewReader(output))
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
stop, err := onLine(line)
if err != nil {
return err
}
if stop {
break
}
}
return nil
}
func (self *FakeCmdObjRunner) ExpectFunc(description string, fn func(cmdObj *CmdObj) bool, output string, err error) *FakeCmdObjRunner {
self.mutex.Lock()
defer self.mutex.Unlock()
self.expectedCmds = append(self.expectedCmds, CmdObjMatcher{
test: fn,
output: output,
err: err,
description: description,
})
return self
}
func (self *FakeCmdObjRunner) ExpectArgs(expectedArgs []string, output string, err error) *FakeCmdObjRunner {
description := fmt.Sprintf("matches args %s", strings.Join(expectedArgs, " "))
self.ExpectFunc(description, func(cmdObj *CmdObj) bool {
return slices.Equal(expectedArgs, cmdObj.GetCmd().Args)
}, output, err)
return self
}
func (self *FakeCmdObjRunner) ExpectGitArgs(expectedArgs []string, output string, err error) *FakeCmdObjRunner {
description := fmt.Sprintf("matches git args %s", strings.Join(expectedArgs, " "))
self.ExpectFunc(description, func(cmdObj *CmdObj) bool {
return slices.Equal(expectedArgs, cmdObj.GetCmd().Args[1:])
}, output, err)
return self
}
func (self *FakeCmdObjRunner) CheckForMissingCalls() {
self.mutex.Lock()
defer self.mutex.Unlock()
remaining := self.remainingExpectedCmds()
if len(remaining) > 0 {
self.t.Errorf(
"expected %d more command(s) to be run. Remaining commands:\n%s",
len(remaining),
strings.Join(
lo.Map(remaining, func(cmdObj CmdObjMatcher, _ int) string {
return cmdObj.description
}),
"\n",
),
)
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/pkg/commands/oscommands/cmd_obj_runner.go | pkg/commands/oscommands/cmd_obj_runner.go | package oscommands
import (
"bufio"
"bytes"
"io"
"os/exec"
"regexp"
"strings"
"time"
"github.com/go-errors/errors"
"github.com/jesseduffield/lazygit/pkg/utils"
"github.com/sasha-s/go-deadlock"
"github.com/sirupsen/logrus"
)
type ICmdObjRunner interface {
Run(cmdObj *CmdObj) error
RunWithOutput(cmdObj *CmdObj) (string, error)
RunWithOutputs(cmdObj *CmdObj) (string, string, error)
RunAndProcessLines(cmdObj *CmdObj, onLine func(line string) (bool, error)) error
}
type cmdObjRunner struct {
log *logrus.Entry
guiIO *guiIO
}
var _ ICmdObjRunner = &cmdObjRunner{}
func (self *cmdObjRunner) Run(cmdObj *CmdObj) error {
if cmdObj.Mutex() != nil {
cmdObj.Mutex().Lock()
defer cmdObj.Mutex().Unlock()
}
if cmdObj.GetCredentialStrategy() != NONE {
return self.runWithCredentialHandling(cmdObj)
}
if cmdObj.ShouldStreamOutput() {
return self.runAndStream(cmdObj)
}
_, err := self.RunWithOutputAux(cmdObj)
return err
}
func (self *cmdObjRunner) RunWithOutput(cmdObj *CmdObj) (string, error) {
if cmdObj.Mutex() != nil {
cmdObj.Mutex().Lock()
defer cmdObj.Mutex().Unlock()
}
if cmdObj.GetCredentialStrategy() != NONE {
err := self.runWithCredentialHandling(cmdObj)
// for now we're not capturing output, just because it would take a little more
// effort and there's currently no use case for it. Some commands call RunWithOutput
// but ignore the output, hence why we've got this check here.
return "", err
}
if cmdObj.ShouldStreamOutput() {
err := self.runAndStream(cmdObj)
// for now we're not capturing output, just because it would take a little more
// effort and there's currently no use case for it. Some commands call RunWithOutput
// but ignore the output, hence why we've got this check here.
return "", err
}
return self.RunWithOutputAux(cmdObj)
}
func (self *cmdObjRunner) RunWithOutputs(cmdObj *CmdObj) (string, string, error) {
if cmdObj.Mutex() != nil {
cmdObj.Mutex().Lock()
defer cmdObj.Mutex().Unlock()
}
if cmdObj.GetCredentialStrategy() != NONE {
err := self.runWithCredentialHandling(cmdObj)
// for now we're not capturing output, just because it would take a little more
// effort and there's currently no use case for it. Some commands call RunWithOutputs
// but ignore the output, hence why we've got this check here.
return "", "", err
}
if cmdObj.ShouldStreamOutput() {
err := self.runAndStream(cmdObj)
// for now we're not capturing output, just because it would take a little more
// effort and there's currently no use case for it. Some commands call RunWithOutputs
// but ignore the output, hence why we've got this check here.
return "", "", err
}
return self.RunWithOutputsAux(cmdObj)
}
func (self *cmdObjRunner) RunWithOutputAux(cmdObj *CmdObj) (string, error) {
self.log.WithField("command", cmdObj.ToString()).Debug("RunCommand")
if cmdObj.ShouldLog() {
self.logCmdObj(cmdObj)
}
t := time.Now()
output, err := sanitisedCommandOutput(cmdObj.GetCmd().CombinedOutput())
if err != nil {
self.log.WithField("command", cmdObj.ToString()).Error(output)
}
self.log.Infof("%s (%s)", cmdObj.ToString(), time.Since(t))
return output, err
}
func (self *cmdObjRunner) RunWithOutputsAux(cmdObj *CmdObj) (string, string, error) {
self.log.WithField("command", cmdObj.ToString()).Debug("RunCommand")
if cmdObj.ShouldLog() {
self.logCmdObj(cmdObj)
}
t := time.Now()
var outBuffer, errBuffer bytes.Buffer
cmd := cmdObj.GetCmd()
cmd.Stdout = &outBuffer
cmd.Stderr = &errBuffer
err := cmd.Run()
self.log.Infof("%s (%s)", cmdObj.ToString(), time.Since(t))
stdout := outBuffer.String()
stderr, err := sanitisedCommandOutput(errBuffer.Bytes(), err)
if err != nil {
self.log.WithField("command", cmdObj.ToString()).Error(stderr)
}
return stdout, stderr, err
}
func (self *cmdObjRunner) RunAndProcessLines(cmdObj *CmdObj, onLine func(line string) (bool, error)) error {
if cmdObj.Mutex() != nil {
cmdObj.Mutex().Lock()
defer cmdObj.Mutex().Unlock()
}
if cmdObj.GetCredentialStrategy() != NONE {
return errors.New("cannot call RunAndProcessLines with credential strategy. If you're seeing this then a contributor to Lazygit has accidentally called this method! Please raise an issue")
}
if cmdObj.ShouldLog() {
self.logCmdObj(cmdObj)
}
t := time.Now()
cmd := cmdObj.GetCmd()
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return err
}
scanner := bufio.NewScanner(stdoutPipe)
scanner.Split(utils.ScanLinesAndTruncateWhenLongerThanBuffer(bufio.MaxScanTokenSize))
if err := cmd.Start(); err != nil {
return err
}
for scanner.Scan() {
line := scanner.Text()
stop, err := onLine(line)
if err != nil {
stdoutPipe.Close()
return err
}
if stop {
stdoutPipe.Close() // close the pipe so that the called process terminates
break
}
}
if scanner.Err() != nil {
stdoutPipe.Close()
return scanner.Err()
}
_ = cmd.Wait()
self.log.Infof("%s (%s)", cmdObj.ToString(), time.Since(t))
return nil
}
func (self *cmdObjRunner) logCmdObj(cmdObj *CmdObj) {
self.guiIO.logCommandFn(cmdObj.ToString(), true)
}
func sanitisedCommandOutput(output []byte, err error) (string, error) {
outputString := string(output)
if err != nil {
// errors like 'exit status 1' are not very useful so we'll create an error
// from the combined output
if outputString == "" {
return "", utils.WrapError(err)
}
return outputString, errors.New(outputString)
}
return outputString, nil
}
type cmdHandler struct {
stdoutPipe io.Reader
stdinPipe io.Writer
close func() error
}
func (self *cmdObjRunner) runAndStream(cmdObj *CmdObj) error {
return self.runAndStreamAux(cmdObj, func(handler *cmdHandler, cmdWriter io.Writer) {
go func() {
_, _ = io.Copy(cmdWriter, handler.stdoutPipe)
}()
})
}
func (self *cmdObjRunner) runAndStreamAux(
cmdObj *CmdObj,
onRun func(*cmdHandler, io.Writer),
) error {
var cmdWriter io.Writer
var combinedOutput bytes.Buffer
if cmdObj.ShouldSuppressOutputUnlessError() {
cmdWriter = &combinedOutput
} else {
cmdWriter = self.guiIO.newCmdWriterFn()
}
if cmdObj.ShouldLog() {
self.logCmdObj(cmdObj)
}
self.log.WithField("command", cmdObj.ToString()).Debug("RunCommand")
cmd := cmdObj.GetCmd()
var stderr bytes.Buffer
cmd.Stderr = io.MultiWriter(cmdWriter, &stderr)
var handler *cmdHandler
var err error
if cmdObj.ShouldUsePty() {
handler, err = self.getCmdHandlerPty(cmd)
} else {
handler, err = self.getCmdHandlerNonPty(cmd)
}
if err != nil {
return err
}
var stdout bytes.Buffer
handler.stdoutPipe = io.TeeReader(handler.stdoutPipe, &stdout)
defer func() {
if closeErr := handler.close(); closeErr != nil {
self.log.Error(closeErr)
}
}()
t := time.Now()
onRun(handler, cmdWriter)
err = cmd.Wait()
self.log.Infof("%s (%s)", cmdObj.ToString(), time.Since(t))
if err != nil {
if cmdObj.suppressOutputUnlessError {
_, _ = self.guiIO.newCmdWriterFn().Write(combinedOutput.Bytes())
}
errStr := stderr.String()
if errStr != "" {
return errors.New(errStr)
}
if cmdObj.ShouldIgnoreEmptyError() {
return nil
}
stdoutStr := stdout.String()
if stdoutStr != "" {
return errors.New(stdoutStr)
}
return errors.New("Command exited with non-zero exit code, but no output")
}
return nil
}
type CredentialType int
const (
Password CredentialType = iota
Username
Passphrase
PIN
Token
)
// Whenever we're asked for a password we return a nil channel to tell the
// caller to kill the process.
var failPromptFn = func(CredentialType) <-chan string {
return nil
}
func (self *cmdObjRunner) runWithCredentialHandling(cmdObj *CmdObj) error {
promptFn, err := self.getCredentialPromptFn(cmdObj)
if err != nil {
return err
}
return self.runAndDetectCredentialRequest(cmdObj, promptFn)
}
func (self *cmdObjRunner) getCredentialPromptFn(cmdObj *CmdObj) (func(CredentialType) <-chan string, error) {
switch cmdObj.GetCredentialStrategy() {
case PROMPT:
return self.guiIO.promptForCredentialFn, nil
case FAIL:
return failPromptFn, nil
default:
// we should never land here
return nil, errors.New("runWithCredentialHandling called but cmdObj does not have a credential strategy")
}
}
// runAndDetectCredentialRequest detect a username / password / passphrase question in a command
// promptUserForCredential is a function that gets executed when this function detect you need to fill in a password or passphrase
// The promptUserForCredential argument will be "username", "password" or "passphrase" and expects the user's password/passphrase or username back
func (self *cmdObjRunner) runAndDetectCredentialRequest(
cmdObj *CmdObj,
promptUserForCredential func(CredentialType) <-chan string,
) error {
// setting the output to english so we can parse it for a username/password request
cmdObj.AddEnvVars("LANG=C", "LC_ALL=C", "LC_MESSAGES=C")
return self.runAndStreamAux(cmdObj, func(handler *cmdHandler, cmdWriter io.Writer) {
tr := io.TeeReader(handler.stdoutPipe, cmdWriter)
go utils.Safe(func() {
self.processOutput(tr, handler.stdinPipe, promptUserForCredential, handler.close, cmdObj)
})
})
}
func (self *cmdObjRunner) processOutput(
reader io.Reader,
writer io.Writer,
promptUserForCredential func(CredentialType) <-chan string,
closeFunc func() error,
cmdObj *CmdObj,
) {
checkForCredentialRequest := self.getCheckForCredentialRequestFunc()
task := cmdObj.GetTask()
scanner := bufio.NewScanner(reader)
scanner.Split(bufio.ScanBytes)
for scanner.Scan() {
newBytes := scanner.Bytes()
askFor, ok := checkForCredentialRequest(newBytes)
if ok {
responseChan := promptUserForCredential(askFor)
if responseChan == nil {
// Returning a nil channel means we should terminate the process.
// We achieve this by closing the pty that it's running in. Note that this won't
// work for the case where we're not running in a pty (i.e. on Windows), but
// in that case we'll never be prompted for credentials, so it's not a concern.
if err := closeFunc(); err != nil {
self.log.Error(err)
}
break
}
if task != nil {
task.Pause()
}
toInput := <-responseChan
if task != nil {
task.Continue()
}
// If the return data is empty we don't write anything to stdin
if toInput != "" {
_, _ = writer.Write([]byte(toInput))
}
}
}
}
// having a function that returns a function because we need to maintain some state inbetween calls hence the closure
func (self *cmdObjRunner) getCheckForCredentialRequestFunc() func([]byte) (CredentialType, bool) {
var ttyText strings.Builder
prompts := map[string]CredentialType{
`Password:`: Password,
`.+'s password:`: Password,
`Password\s*for\s*'.+':`: Password,
`Username\s*for\s*'.+':`: Username,
`Enter\s*passphrase\s*for\s*key\s*'.+':`: Passphrase,
`Enter\s*PIN\s*for\s*.+\s*key\s*.+:`: PIN,
`Enter\s*PIN\s*for\s*'.+':`: PIN,
`.*2FA Token.*`: Token,
}
compiledPrompts := map[*regexp.Regexp]CredentialType{}
for pattern, askFor := range prompts {
compiledPattern := regexp.MustCompile(pattern)
compiledPrompts[compiledPattern] = askFor
}
newlineRegex := regexp.MustCompile("\n")
// this function takes each word of output from the command and builds up a string to see if we're being asked for a password
return func(newBytes []byte) (CredentialType, bool) {
_, err := ttyText.Write(newBytes)
if err != nil {
self.log.Error(err)
}
for pattern, askFor := range compiledPrompts {
if match := pattern.Match([]byte(ttyText.String())); match {
ttyText.Reset()
return askFor, true
}
}
if indices := newlineRegex.FindIndex([]byte(ttyText.String())); indices != nil {
newText := []byte(ttyText.String()[indices[1]:])
ttyText.Reset()
ttyText.Write(newText)
}
return 0, false
}
}
type Buffer struct {
b bytes.Buffer
m deadlock.Mutex
}
func (b *Buffer) Read(p []byte) (n int, err error) {
b.m.Lock()
defer b.m.Unlock()
return b.b.Read(p)
}
func (b *Buffer) Write(p []byte) (n int, err error) {
b.m.Lock()
defer b.m.Unlock()
return b.b.Write(p)
}
func (self *cmdObjRunner) getCmdHandlerNonPty(cmd *exec.Cmd) (*cmdHandler, error) {
stdoutReader, stdoutWriter := io.Pipe()
cmd.Stdout = stdoutWriter
buf := &Buffer{}
cmd.Stdin = buf
if err := cmd.Start(); err != nil {
return nil, err
}
return &cmdHandler{
stdoutPipe: stdoutReader,
stdinPipe: buf,
close: func() error { return nil },
}, nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.